Initializing C structure that is an index of an array of structures

Viewed 463

I have this structure:

typedef struct {
    char* name;
    int number;
} Customer;

I also have an array of Customer structures. I would like to initialize each index of the array with a Customer structure containing a name and a number. Here is the code for that:

Customer* customerArray = malloc (5 * sizeof(Customer));
customerArray[0] = { "Name", 1 };

I'm getting a compiler error that says "Expected expression" and nothing else. This happens for each array index that I try to initialize in this way. However, if I do this:

Customer myCustomer = { "Name", 1 };

I do not get a compiler error. Why do I only get this error when I try to initialize a structure that's in an array?

1 Answers

This syntax is not valid:

customerArray[0] = { "Name", 1 };

Because this is not an initialization but an assignment, and a braced set of values can only be used when initializing.

You can either set each field individually:

customerArray[0].name = "Name";
customerArray[0].number = 1;

Or you can do the assignment with a compound literal:

customerArray[0] = (Customer){ "Name", 1 };
Related