I can’t understand how the following structure elements are being initialized

I can’t understand how the following structure elements are being initialized.

MSG m = {4, 1, 0};.

MSG has two elements: one is of type int and other one is an array of type short that’s already been initialized.
Which elements of m are assigned the values 4, 1 and 0?
Here is the listing of the code taken from the book TCP IP in C 2nd Ed. (Page No. xi, Preface);

typedef struct {
    int a;
    short s[2];
} MSG;
MSG *mp, m = {4, 1, 0};
char *fp, *tp;
mp = (MSG *) malloc(sizeof(MSG));
for (fp = (char *)m.s, tp = (char *)mp->s; tp < (char *)(mp+1);)
  *tp++ = *fp++;

Although I’ve read over C a reference manual but I couldn’t find the solution. I might have overlooked it but I can’t proceed until I clear my understanding how the initialization is done where an element of m is a three element array of type short int itself.

2

Do it like this:

MSG m = {
.a = 4 
.s = {1, 0}
};

It’s clearer, it works, and you won’t have to fry brain cells figuring out what it does every time you look at it.

1

Correct way to initialize the structure is shown in Robert’s answer, but I guess the question is “how this initialization works?”

In fact, the C reference does describe structure initialization and it allows you to not use extra curly braces as long as the number of elements in initializer is less or equal to number of elements in aggregate. Following snippets are equivalent:

MSG m = {4, 1, 0};

and

MSG m = {4, {1, 0}};

But this one is incorrect, since a element is not an aggregate:

MSG m = {{4}, {1, 0}};

I only have Russian copy of KR, so here’s a rough translation: Aggregate initializer starts with curly and all the items inside those braces are considered part of that aggregate. If it doesn’t start with curly, it takes as much elements as it can hold (or less if there is not enough elements).

Surprisingly, the following two snippets are also correct:

MSG m = {4, 1};

and

MSG m = {4, {1}};

2

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *