Structures: a yes/no question.

This is a discussion on Structures: a yes/no question. within the C Programming forums, part of the General Programming Boards category; I want to know if you can have a struct with a component that is a pointer to an array ...

  1. #1
    Not bad at Crack Attack!
    Join Date
    Aug 2003
    Posts
    45

    Structures: a yes/no question.

    I want to know if you can have a struct with a component that is a pointer to an array of indeterminate length? Say something like:

    Code:
    struct log {
      int registration_number;
      int *scores;
    }
    where "scores" is not necessarily the same from log to log. I suppose you must be able to do this if you can include strings which differ from struct to struct in a struct, which I think you can.

    Yay or nay?

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,788
    Yes, but you probably want some variable in that struct to store the actual number of elements pointed to by the pointer...

    Code:
    struct log {
      int registration_number;
      int size;
      int *scores;
    }
    Whenever you dynamically allocate an array of X ints for example and store that pointer in scores, you can set size to X as well. When you later attempt to access scores you will then know how many elements there are in this particular instance of struct log so you don't end up doing some loop that overruns memory.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Not bad at Crack Attack!
    Join Date
    Aug 2003
    Posts
    45

    Thanks

    Thankyou. I was aware of the size issue and I forgot to include an int number_of_games thingie.

    Thanks again

    (PS: I broke #1 rule of the board and didn't check elsewhere before posting - it was in prelude's (excellent) corner in her section about structures. Sincere apologies to all.)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Exam Question - Possible Mistake?
    By Richie T in forum C++ Programming
    Replies: 15
    Last Post: 05-08-2006, 03:44 PM
  2. Replies: 4
    Last Post: 02-02-2003, 04:45 AM
  3. Question about structures
    By Randoon in forum C Programming
    Replies: 2
    Last Post: 12-12-2002, 10:47 PM
  4. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 02:57 PM
  5. Question about efficiency... structures and stuff
    By rmullen3 in forum C++ Programming
    Replies: 2
    Last Post: 01-05-2002, 12:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21