-1

I have the following structs:

typedef struct cxt_simple_socket_address_s
{
        int is_ipv6;
        cs_inaddr_t ip;
        unsigned short ip_port;
} cxt_simple_socket_address_t;

typedef struct cs_inaddr
{
        union {
            struct in6_addr in6;
            struct
            {
                uint8_t pad[12];
                uint32_t in;
            };
            long long as_longs[2];
        };
} cs_inaddr_t;

I would like to initialize a struct of type cxt_simple_socket_address_t upon declaration:

cxt_simple_socket_address_t any = {.in = INADDR_ANY};

This line doesn't compile. I have tried countless other variations, but I believe my problem is than .in is found within an anonymous struct inside an anonymous union.

HELP?

Jenz
  • 8,280
  • 7
  • 44
  • 77

3 Answers3

1

Firstly order of declaration is wrong.
struct cs_inaddr should be declared first, followed by struct cxt_simple_socket_address_s.
Since its is nested Structure (compiler will look for definition of cs_inaddr first).

typedef struct cs_inaddr
{
    union {
        struct in6_addr in6;
        struct
        {
            unsigned char pad[12];
            unsigned int in;
        };
        long long as_longs[2];
    };
} cs_inaddr_t;

typedef struct cxt_simple_socket_address_s
{
    int is_ipv6;
    cs_inaddr_t ip;
    unsigned short ip_port;
} cxt_simple_socket_address_t;

Initialization of variable should be as:

cxt_simple_socket_address_t any = {.ip = {.in = INADDR_ANY}};

Tested it using the below:

cxt_simple_socket_address_t any = {.ip = {.in = 100}};
printf("%d\n", any.ip.in);

Output: 100

Note:
The nested (inner) structure can be anonymous, since the outer structure has a tag name.
Hence can be accessed.

Saurabh Meshram
  • 8,106
  • 3
  • 23
  • 32
0

cxt_simple_socket_address_s doesn't contain any field naming in. Are you mean

cxt_simple_socket_address_t any = {ip.in = INADDR_ANY};

?

Ves
  • 1,212
  • 1
  • 9
  • 19
0

First of all you need to move the whole declaration of struct cs_inaddr before cxt_simple_socket_address_t in order to make it visible.

Then initialize using:

cxt_simple_socket_address_t any = {.ip.in = INADDR_ANY};

Also note that anonymous unions are introduced in C11 or as a gcc extension.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • The structs order is not as it is in real code of course. it was just for you to understand the structure of the struct I am trying to initialize. I am compiling with gcc – Tal Zohar Sep 01 '14 at 11:35
  • Then `cxt_simple_socket_address_t any = {.ip.in = INADDR_ANY};` will work as expected. – David Ranieri Sep 01 '14 at 11:38
  • Well it doesn't. I get the following error: error: unknown field âinâ specified in initializer cc1: warnings being treated as errors src/simple_socket_tcp_async.c:344: error: missing braces around initializer src/simple_socket_tcp_async.c:344: error: (near initialization for âany.ip.â) – Tal Zohar Sep 01 '14 at 11:43