On the differences between C language common body and structure

  • 2020-05-12 02:57:40
  • OfStack

The difference between a Shared body and a structural body

The appropriate:

Use the union keyword

The memory length in the pool is the length of the longest internal data type.

The address of the common body and the address of the internal member variables are the same address

Structure size:

A member of a structure whose size is equal to the offset of the last member + the size of the last member + the number of padding bytes at the end.

Structure offset: the distance between the actual address of a member and the first address of the structure.

Struct byte alignment: each member's offset relative to the first address of the structure must be an integer multiple of the memory occupied by the current member, if it is not preceded by padding bytes. The size of the structure is an integer multiple of the widest member inside.

The appropriate


#include <stdio.h>
//gcc Let different types of variables share memory addresses  , with 1 The only time 1 Individual members valid 
union data{ 
  int a;
  char b;
  int c;
};


int main(){
  union data data_1 = {1};// Fill in only when initializing 1 A value. ( with 1 The only time 1 Individual members valid )
  data_1.b = 'c';
  data_1.a = 10;// After the assignment is valid. The previous assignment is overridden 
  // Print the address and find the same direction 1 An address 
  printf("%p\n%p\n%p\n",&data_1.a,&data_1.a,&data_1.a);
  return 0;
}


Related articles: