C++ | View the offset of the member variables in the structure in memory (structure memory alignment)

The memory is not arranged in a single sequence during use, but is aligned according to certain established rules to facilitate quick access.
There are three principles for memory alignment:

  • Data member alignment: According to its own size, the member is stored starting from the memory address that is an integral multiple of its own size (with the first element stored at position 0 as a reference)
  • Alignment of structure members: If the structure members are included, the storage location of the structure members starts from the address that is an integer multiple of the maximum value of its internal members.
  • Alignment of the total size of the structure: it must be an integer multiple of its largest internal member, and any shortage must be made up.

The members in the structure are stored in the order of declaration, and the address of the first member is the same as the address of the entire structure.
Unless otherwise specified, it is aligned according to the member with the largest size in the structure (if there is a double member, it is aligned according to 8 bytes.)

After c++11, two keywords alignas and alignof are introduced. Among them, alignof can calculate the alignment of the type, and alignas can specify the alignment of the structure.
If alignas is smaller than the minimum unit of natural alignment, it will be ignored.

offsetofIt is convenient to view the offset of member variables in the structure
and to learn the memory alignment of the structure.

#include<iostream>
#include<stddef.h>
#include<bits/stdc++.h>
using namespace std;
struct alignas(4) Info2{
    uint8_t a;
    uint32_t b;
    uint16_t c;
    //uint16_t d;
}mys;

int main(){
  cout<<sizeof(Info2)<<endl;
  Info2 temp;
  int offset_a = offsetof(Info2, a);
  int offset_b = offsetof(Info2, b);
  int offset_c = offsetof(Info2, c);
  //int offset_d = offsetof(Info2, d);
  cout << "Offset of a: " << offset_a << endl;
  cout << "Offset of b: " << offset_b << endl;
  cout << "Offset of c: " << offset_c << endl;
  //cout << "Offset of d: " << offset_d << endl;
  return 0;
}

Guess you like

Origin blog.csdn.net/holly_Z_P_F/article/details/132199883