0

I can not really resolve, why do I get the unexpected return value in this code:

#include <stdio.h>

typedef union ku {
    struct {
        int x;
        int y;
    } sd;
    int id;
} ku_type;

ku_type kuReturner() {
    ku_type ku;
    ku.sd.x = 11;
    ku.sd.y = 22;
    ku.id = 99;
    return ku;
}

int main()
{
    ku_type ku;
    ku = kuReturner();
    
    // returns '99', it is not expected value
    // expected value must be '11'
    printf("%d", ku.sd.x);

    return 0;
}

I have tried to define struct outside the union and create a struct variable inside union, but the result was always the same. Where do I have a mistake?

timrau
  • 22,578
  • 4
  • 51
  • 64
Manium
  • 55
  • 10
  • 3
    `// expected value must be '11'` Why? What makes you think that should be true? Do you know what a union is compared to a struct? Given your expectation, why do you use a union at all? – Gerhardh Jun 30 '22 at 10:55
  • If you remove the line `ku.id = 99;` you get the right answer. It's `99` because of that line, which overwrites the `11`. – Weather Vane Jun 30 '22 at 11:00
  • 3
    You seem to misunderstand how unions work in C. All member of a union share the same memory. So `sd` and `id` members are both using the same memory. The last value you write to any of the members is what will be stored in that memory. Perhaps what you really want is a structure? – Some programmer dude Jun 30 '22 at 11:03
  • Yes you are right, I have misunderstand the storing of union. Why you guys do not use the answer button? :D Do I understand it right: In according to "Unions only allocate enough space to store the largest field listed, and all fields are stored at the same space" means, I am overwriting the allocated memory every time I save a value to one of the union element? – Manium Jun 30 '22 at 11:15
  • Yes, you are getting it right now. To use unions properly you need to store information which member was used last unless you are using it especially for type punning. – Gerhardh Jun 30 '22 at 11:17
  • I think the answers to the suggested duplicate question explain it in great detail. – Gerhardh Jun 30 '22 at 11:17
  • Yep. ;-) Me too. @Gerhardh But Manium, with good reasoning why your question is different and not answered by the total of posts there.... just explain in your question. – Yunnosch Jun 30 '22 at 11:18
  • @Yunnosch because I have misunderstand the allocation of the union. Just got the knowledge based on "it is the same like struct, just the memory allocation is not dedicated". I have ignored a lot of content about memory allocation. – Manium Jun 30 '22 at 11:22
  • They look so terribly similar. You are not the first one to be misled/confused by that. I just want to make sure that you got your answer, because I caused the closing (special privilege which I try to use carefully). – Yunnosch Jun 30 '22 at 12:03

0 Answers0