简体   繁体   中英

Weird behaviour in C involving unions inside structs

When I use unions inside structures I observed a weird bahaviour, I don't know if that should be the case or not. Basicall when you have a union with two members inside a struct for some reason I can't access both elements I only get the first one, whether I asked for the first or second member.

I wrote a test class:

#include <stdio.h>  
#include <stdlib.h>

struct uni {
  char *a;
  char *b;
};

union stru {
  struct uni unInStruc1;
  struct uni unInStruc2;
  char *test;

};

int main() {
  union stru new = {{"string 1 in A", "string 2 in A"}
                    , {"string 1 in B","string 2 in B"}
                    , "test"};

  printf("%s", new.unInStruc2.a);
  printf("%s", new.unInStruc2.b);
  printf("%s", new.unInStruc1.a);
  printf("%s", new.unInStruc1.b);
  printf("%s", new.test);

}

this code outputs:

string 1 in B
string 1 in B
string 1 in A
string 1 in A
test

even though in the code I'm trying to access b what I get is a . I can't access the second string b in any union.

When I change the initialization to

union stru new = {{"string 1 in A", "string 2 in A"}
                    , {NULL,"string 2 in B"}
                    , "test"};

Sometimes I get seg fault and sometimes the output would be:

(null)
(null)
string 1 in A
string 1 in A
test

Can somebody explain this if I'm missing something or anything

First of all what is the purpose of your code? The memory occupied by the union will be large enough to hold the largest member of the union. You are assigning different value to the same location and the memory location holds the last value. When you assign new values to different members, the older member values get corrupted. In your code, you are assigning 'test' to union member test at the end - so only that is not corrupted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM