+ 2
What is an union? How do they help in improvement of memory management?
what's the difference between structures and unions?
2 ответов
+ 3
You can put in the same location content of different types. You have to know the type of what you have stored in the union (so often you put it in a struct with a type tag...).
Why is this important? Not really for space gains. Yes, you can gain some bits or do some padding, but that's not the main point anymore.
It's for type safety, it enables you to do some kind of 'dynamic typing': the compiler knows that your content may have different meanings and the precise meaning of how your interpret it is up to you at run-time. If you have a pointer that can point to different types, you MUST use a union, otherwise you code may be incorrect due to aliasing problems (the compiler says to itself "oh, only this pointer can point to this type, so I can optimize out those accesses...", and bad things can happen).
But all the difference lies by the usage need of the memory. Best usage of the union can be seen in the processes of unix where we make use of signals.
But that is not full knowledge at all. In structure you can access all the variable inside of a structure at samr time. But in union Due to storing data on same location you cannot access all the variable at same time.
Structure is most used data format on data structure.
- 1
Union is nothing but a keyword. The memory allocation is shared between the all elements. But in structure memory allocation is made separately.