본문 바로가기

C

C: union # struct

728x90
반응형

union

  - 다양한 타입의 변수를 담을 수 있다.

  - * 메모리를 공유한다.

      union 내에 선언된 가장 큰 변수 타입의 크기만큼을 메모리로 할당 받고, 이 메모리를 union 내의 변수들이 공유

      -> 값이 덮어 씌여진다.

   - struct와 모양은 유사하나 각 변수들이 메모리 공간을 개별로 할당 받는 것이 아니라,

     선언되는 변수가 그 메모리 공간을 차지하게 된다.

   - 메모리를 효율적으로 사용해야되는 상황에서, 배타적으로 사용될 변수들을 정의할 수 있는 경우에 유용

 

아래는 ChatGPT 설명

 

es, the C programming language includes a data type known as a "union." A union is a special data type available in C (and C++) that allows you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. This makes unions useful for storing data that may be one of several types but never simultaneously.

Here's an example of how a union might be declared in C:

union Data {
    int i;
    float f;
    char str[20];
};

union Data data;
data.i = 10;       // data now contains an integer
data.f = 220.5;    // data now contains a float, integer value is overwritten

In this example, the union Data can store an integer, a float, or a string of characters. However, because all of them are stored in the same memory location, the value of data.i is overwritten when data.f is assigned a new value. Unions are particularly useful in situations where variables are used exclusively under certain conditions, thus saving memory.

 

Q: I don't understand the overwriting of value. Explain in detail comparing with struct

 

A: The concept of memory management in unions versus structs in C can be a bit tricky, so let's delve into it with more detail and a direct comparison.

 

Structs in C

A struct (structure) is a composite data type in C that allows you to group different data types together under a single type. Each member within a struct has its own unique memory location, and the size of a struct is at least the sum of the sizes of its members (often more due to padding for alignment purposes). When you assign values to members of a struct, each member retains its value independently of the others.

Here is an example of a struct:

struct ExampleStruct {
    int i;
    float f;
    char str[20];
};

struct ExampleStruct myStruct;
myStruct.i = 5;
myStruct.f = 3.14;
strcpy(myStruct.str, "Hello");

 

In this example, myStruct contains an integer, a float, and a string. Each occupies a different part of memory within myStruct. The integer i does not affect f or str, and vice versa.

Unions in C

A union, on the other hand, allows multiple members to share the same memory location. This means that at any point in time, only one member can hold a value. The size of a union is equal to the size of its largest member because there is only one memory location used to store whichever member is currently being used.

Here is an example using the same types as in the struct:

union ExampleUnion {
    int i;
    float f;
    char str[20];
};

union ExampleUnion myUnion;
myUnion.i = 5;      // The memory location is now storing the integer value 5
myUnion.f = 3.14;   // The same memory location now stores the float value 3.14, overwriting the integer

 

When you assign 5 to myUnion.i, the memory location for the union stores the integer. But as soon as you assign 3.14 to myUnion.f, it overwrites the memory location with this new float value, because both i and f share the exact same memory location.

Why Use a Union?

The key reason to use a union is memory efficiency. If you know that several different types of data will not be used at the same time, a union allows you to reuse the same memory for different purposes. This is particularly useful in memory-constrained environments or when manipulating data at a low level, such as hardware registers or protocol unions where different kinds of data might be interpreted from the same memory location depending on some condition.

Summary

  • Structs allocate separate memory for each of its members.
  • Unions share the same memory among all of its members.
728x90
반응형