Using designated initializers with unnamed nested data types

I am wondering if it is possible to use assigned initializers in unnamed data elements of structures ... (Yikes, a sip, but yes, this is the cleanest way to do what I'm trying to do ...). If I have:

typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main.a64 = { 0, 0 }, .otherval = 3 };

and I'm trying to compile, I get an error:

tst3.c:16: error: unknown fielda64specified in initializer

I also tried using .main..a64, but I am having other problems. This is with gcc 4.4. Unfortunately, it is MainStructused throughout the code, so naming the union will require changing hundreds of files, so I would like to avoid this. I would also like to avoid any assumptions about the position MainStructwithin OtherStruct, if possible.

0
1

, .main instance:

typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main = {.a64 = { 0, 0 }}, .otherval = 3 };

:

#include <stdio.h>
#include <stdint.h>

typedef struct MainStruct {
    union {
         uint8_t   a8[16];
         uint64_t  a64[2];
    };
    uint64_t       i64;
} MainStruct_t;

typedef struct OtherStruct {
    MainStruct_t main;
    int          otherval;
} OtherStruct_t;

OtherStruct_t instance = { .main = {.a64 = { 5, 10 }}, .otherval = 3 };

int main(void)
{
    printf("%d, %d\n", (int) instance.main.a64[0], (int) instance.main.a64[1]);
    printf("%d\n", instance.otherval);

}

gcc -std=c11 -Wall -Wextra -Wpedantic, :

5, 10
3

Update

C99, C99 . :

#include <stdio.h>

struct Inner {
    int x;
    int arr[2];
};

struct Outer {
    char id[100];
    struct Inner state;
};

int main(void)
{
    struct Outer instance = { .id = "first",
                              .state = {.x = 5, .arr[0] = 1, .arr[1] = 2 }};

    printf("instance id: %s\n", instance.id);
    printf("instance state.x = %d\n", instance.state.x);
    printf("instance state.arr[0] = %d\n", instance.state.arr[0]);
    printf("instance state.arr[1] = %d\n", instance.state.arr[1]);

    return 0;
}

gcc -std=c99 -Wall -Wextra -Wpedantic, :

instance id: first
instance state.x = 5
instance state.arr[0] = 1
instance state.arr[1] = 2

, OP:

OtherStruct_t instance = { .main.a64 = { 0, 0 }, .otherval = 3 };

C99, C11, , .

C99, GNU. , , gcc 4.6. ; , , , OP.

+1

Source: https://habr.com/ru/post/1677319/


All Articles