Arnaud Rochez Arnaud Rochez - 1 year ago 89
C Question

How can I initialize an array of a struct inside another struct?

so I got the following structs:

typedef struct typeData{
char name[20];
double weightIn;
double weightOut;

typedef struct fifoTable{
unsigned short int start;
unsigned short int end;
dataType data[N];
} fifoTable;

and the following function that is supposed to initialize the structure:

fifoTable *initFifo(){
fifoTable table;
table.start = 0;
table.start = 0;
dataType data[N]; = data;
return table;

The problem I encounter is that I get an error message saying: "assignment to expression with array type". I looked it up so I figured it is not possible to initialize an array inside a struct like this. I found some examples with arrays of char, int etc. But since there are other elements inside the dataType struct, I can't find a way to initialize this table :/ How could I do this?

Thanks for your answers.

Answer Source

This won't work for a number of reasons.

First, an array is not an assignable lvalue. That means it can't appear on the left side of an assignment as you're attempting to do.

Note that initializing (which occurs at the time a variable is defined) is not the same as assigning. For example, you can do this:

int a[3] = { 3, 4, 5 };

But not this:

int a[3] = { 3, 4, 5 };
int b[3];
b = a;

You're also returning a fifoTable from your function while it's declared to return a fifoTable *.

What you probably want is to dynamically allocate memory for your struct, zero it out, and return the pointer. You do that as follows:

fifoTable *initFifo(){
    fifoTable *retval = calloc(1, sizeof(fifoTable));
    if (!retval) {
        perror("calloc failed");
    return retval;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download