Do pointers inside a union share same memory location?

ぐ巨炮叔叔 提交于 2020-03-22 08:56:13

问题


I was going through an article to learn about union and I had understood that the size of a Union depends upon the largest variable size and the variables share the same memory. So the concept was pretty clear for me but in the article author said that using "union" for a binary tree was worthwhile when it had two pointers to point other two child. A question arose in my mind for the "What are applications of union?" section of that article, what would be the possible explanations for pointers inside a union? The link has been given below.

https://www.geeksforgeeks.org/union-c/

So, this is it. Is there anybody who can help me out?


回答1:


in the article author said that using "union" for a binary tree is worthwhile when it had two pointers to point other two child...what would be the possible explanations for pointers inside a union?

I believe you are talking about this code snippet:


struct NODE { 
    bool is_leaf; 
    union { 
        struct
        { 
            struct NODE* left; 
            struct NODE* right; 
        } internal; 
        double data; 
    } info; 
}; 

You misunderstand the author's intent here. They are using a union to implement the two different kinds of nodes in a tree: an internal node that has a left and right pointer and a leaf node which has data. This union shares memory between a struct and a double. It does not share memory between the left and right pointers.




回答2:


I'd also inject that I really don't agree with this author. Just define a struct with two pointers and data, and be done. Use calloc() to obtain the structure and set it all to binary zeros. There's no point in "saving a few bytes of memory" anymore. If you use a union in this way, you are going to screw-up and waste a lot of time debugging.




回答3:


§6.7.2.1 - 16 ISO/IEC 9899:2017

The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), andvice versa.

So yes, all the members of the union, being pointers or other, all share the same address which is consistent with how unions work.

Tested here:

https://wandbox.org/permlink/XdGY4Mrz0gQCfrbv



来源:https://stackoverflow.com/questions/60621603/do-pointers-inside-a-union-share-same-memory-location

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!