Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 444 Vote(s) - 3.56 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Anonymous Union in Struct Initializer

#1
Why does following example not work in C?


#include <stdio.h>

typedef struct {
int x;
} X;

typedef struct {
char y[10];
} Y;

typedef struct {
int pos;
union {
X x;
Y y;
};
} Test;

int main() {
X x = { 65 };
Y y = { "Hallo" };
Test t = { 1, x }; // OK
printf("1: %d %d '%s'\n", t.pos, t.x.x, t.y.y);
Test t2 = { 2, y }; // ERROR
printf("2: %d %d '%s'\n", t2.pos, t2.x.x, t2.y.y);
Test t3 = { 3 }; // OK
printf("3: %d %d '%s'\n", t3.pos, t3.x.x, t3.y.y);
return 0;
}


> main.c: In function ‘main’:<br>
> main.c:25:3: error: incompatible types when initializing type ‘int’ using type ‘Y’<br>
> Test t2 = { 2, y }; // ERROR<br>
> ^


EDIT:
By the way: `t2.y = y;` works
Reply

#2
Because the initializer's type isn't analyzed and matched against the possible members of the `union`.

Instead, you're simply supposed to provide an initializer for the first `union` member.

C11 draft §6.7.9.17:

> Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.

As mentioned, you can use designators to control this:

Test t2 = { 2, .y = y };

should work (that `.y` is a designator, "new" in C99).
Reply

#3
You have to specify that you are initializing a member other than the first:

Test t2 = { 2, { .y = y } } ;

Otherwise the compiler will try to initialize it as if you wrote: `.x = y`
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through