Thread: Initializing array of structs

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    7

    Initializing array of structs

    I'm having a problem initializing members of a struct array. That being said, the problem could very well be before the initialization. I'm still new, so bear with me!

    Here's the relevant pieces of code. Names changed to protect the guilty.

    Code:
    struct Thing {
    int mem1;
    int mem2;
    int mem3;
    int mem4;
    };
    
    struct Thing *things;
    
    void SomeFunc(void) {
    extern struct Thing *things;
    things = malloc(sizeof(struct Thing) * 33);
    /* ...check return of malloc, exit if needed, etc... */
    
    things[0] = {1, 1, 0, 0};
    /* ...etc...*/
    }
    The error I get is "syntax error before '{' token", which is comforting in that it assures me I'm just doing something dumb. Hopefully it's at least clear what I'm trying to do!

    Thanks!

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Use a loop and assign each member.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Nov 2007
    Posts
    7
    Alright, I'll do that.

    Out of curiosity, is there a reason it has to be done like that? I thought one could initialize a struct with the curly braces method. Just wondering why that isn't the case here. Thanks again~

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    You're not initializing, you're assigning. If you made a structure to copy, you could structure assign.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating array of structs
    By knirirr in forum C++ Programming
    Replies: 12
    Last Post: 06-18-2008, 08:30 AM
  2. pointer to array of structs
    By Luken8r in forum C Programming
    Replies: 2
    Last Post: 01-08-2008, 02:05 PM
  3. pointer to array of structs
    By Luken8r in forum C Programming
    Replies: 4
    Last Post: 01-02-2008, 11:20 AM
  4. Initializing a 3D array w/o a loop.
    By funkydude9 in forum C++ Programming
    Replies: 5
    Last Post: 03-04-2004, 11:20 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM