Search code examples
cstructnesteddesignated-initializer

Using a designated initializer to initialize nested struct with a `char []` member


I have the following nested struct definition:

typedef struct {
    int count;
    float cash;
    char item[50];//switch between array and pointer for testing initializers
    //char *item;
}Purchase;

typedef struct {
    int accnt;
    char acct_name[50];
    Purchase purch;
} Acct;

Where for the Purchase struct by itself, the following initializer works:

//Uses member names:
/* 1 */Purchase p = {.count = 4, .cash = 12.56, .item = "thing"};
//  Note: this member:                          ^^^^^^^^^^^^^^^

And for the nested struct Acct the following works:

// No member names:
/* 2 */Acct acct = {100123, "Robert Baily", {15, 12.50, "Tires"}};
//                                                      ^^^^^^^

but when I attempt to use the member name, as in the first example:

// Attempts to use member name, but fails the last one:
/* 3 */Acct acct3 = {.accnt = 100123, .acct_name = "Robert Baily", {acct3.purch.count = 15, acct3.purch.cash = 12.50, acct3.purch.item = "Tires"}};
// error occurs here ->                                                                                                                ^

I get this error: 22, 131 error: array type 'char [50]' is not assignable when using member char item[50]; inPurchase`

And I get this error: 22, 14 error: initializer element is not a compile-time constant When using member char *item; in Purchase (Note only one version of item is part of the struct at any one time, the other is commented)

So, in summary, I can initialize a nested struct okay if not using named assignment statements as in statement /* 2 */ above, but when I attempt to use named assignments as shown for char [] types in statement /* 3 */, it fails.

What am I missing for initializing a char [] or char * when it is a member of the inner struct of a nested struct construct?

I am using the CLANG set to C99


Solution

  • You are trying to compile:

    Acct acct3 = {.accnt = 100123, .acct_name = "Robert Baily", 
               {acct3.purch.count = 15, acct3.purch.cash = 12.50, acct3.purch.item = "Tires"}};
    

    This initializer is not valid because acct3.purch is not a field name of Purchase. You only use the innermost field names when initializing.

    Acct acct3 = {.accnt = 100123, .acct_name = "Robert Baily", 
                  .purch = {.count = 15, .cash = 12.50, .item = "Tires"}};