Holla Tech - Learn

Pointers to Unions
 

A pointer to a union points to the memory location allocated to the union.
A union pointer is declared by using the keyword union and the union tag along with * and the pointer name.
For example, consider the following statements: 

union val {
  int int_num;
  float fl_num;
  char str[20];
};

union val info;
union val *ptr = NULL;
ptr = &info;
ptr->int_num = 10;
printf(“info.int_num is %d”, info.int_num); 

 

When you want to access the union members through a pointer, the -> operator is required.

NOTE!
(*ptr).int_num is the same as ptr->int_num.

Unions as Function Parameters
 

A function can have union parameters that accept arguments by value when a copy of the union variable is all that is needed.

For a function to change the actual value in a union memory location, pointer parameters are required.
For example:

union id {
  int id_num;
  char name[20];
};

void set_id(union id *item) {
  item->id_num = 42;
}

void show_id(union id item) {
  printf(“ID is %d”, item.id_num);

 


Array of Unions
 

An array can store elements of any data type, including unions.
With unions, it is important to keep in mind that only one member of the union can store data for each array element.

After declaring an array of unions, an element is accessible with the index number. The dot operator is then used to access members of the union, as in the program:

union val {
  int int_num;
  float fl_num;
  char str[20];
};

union val nums[10];
int k;

for (k = 0; k < 10; k++) {
  nums[k].int_num = k;
}

for (k = 0; k < 10; k++) {
  printf(“%d  “, nums[k].int_num);

 

An array is a data structure that stores collection values that are all the same type. Arrays of unions allow storing values of different types.
For example:

union type {
  int i_val;
  float f_val;
  char ch_val;
};
union type arr[3];
arr[0].i_val = 42;
arr[1].f_val = 3.14;
arr[2].ch_val = ‘x’

 


BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT