user2790498
user2790498

Reputation: 41

static array initializer during structure initialization

Here is a simplified version of two structs I have:

struct MyStruct1 {
    double d;
}

struct MyStruct2 {
    struct MyStruct1* a;
    int i;
}

I can initialize the second struct as follows:

void InitStruct(struct MyStruct2 pMyStruct2) {
    static struct MyStruct1 A[] = { {.d=12} , {.d=17} , {.d=1} };
    *pMyStruct2 = (struct MyStruct2) { .a = A, .i = 3 };
}

but actually I have to initialize it this way (its because this struct is again part of a bigger structure that shall be initialized at once):

void InitStruct(struct MyStruct2 pMyStruct2) {
    *pMyStruct2 = (struct MyStruct2) { 
        .a = (struct MyStruct1[]) {
            {.d=12} , {.d=17} , {.d=1}},
        .i=3 };
}

Both ways compile without any warnings but the data in the second solution gets corrupted.

I think that the inner array is not static and thus the .a-pointer gets invalid immediately.

Is there another way to tell the compiler to keep the data of the array in the memory?

Upvotes: 0

Views: 528

Answers (1)

Dariusz
Dariusz

Reputation: 22241

C99 standard §6.5.2.5 p6 says that:

The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

In both cases the varables should be properly initialized and valid for usage in the scope they are declared.

If you, however, return the structure from the function by value, the pointer will become invalid.

Here is a sample code I used for testing. Valgrind shows no errors.

#include <stdio.h>

struct MyStruct1 {
  double d;
};

struct MyStruct2 {
  struct MyStruct1* a;
  int i;
};

struct MyStruct1 A[] = { {.d=12} , {.d=17} , {.d=1} };
struct MyStruct2 b1 = { .a = A, .i = 3 };

struct MyStruct2 b2 = { .a = (struct MyStruct1[]) {
                                {.d=12} , {.d=17} , {.d=1}
                            },
                        .i=3 };



int main( void ) {
  struct MyStruct1 B[] = { {.d=12} , {.d=17} , {.d=1} };
  struct MyStruct2 b3 = { .a = B, .i = 3 };

  struct MyStruct2 b4 = { .a = (struct MyStruct1[]) {
                                {.d=12} , {.d=17} , {.d=1}
                            },
                          .i=3 };

  printf("b1->a.d=%1.2f\n", b1.a->d);
  printf("b2->a.d=%1.2f\n", b2.a->d);

  printf("b3->a.d=%1.2f\n", b3.a->d);
  printf("b4->a.d=%1.2f\n", b4.a->d);

}

Upvotes: 1

Related Questions