Bad Example: Byte Alignment

#include<vector>
#include<iostream>
#include<stdio.h>

struct student {
    char c;
    int age;
}__attribute__((packed));
//The result of the codeblock operation in the win32 system: 8, the result after changing the position of char and int is: 5

#pragma pack(push, 1)
struct student1 {
    char c;
    int age;
};
#pragma pack(pop)
// No matter which platform the result is 5
int main() {
    student st;
    student1 st1;
    std::cout << sizeof(st) << std::endl;
    std::cout << sizeof(st1) << std::endl;
    return 0;
}

 In the student structure, if __attribute__((packed)) is added after the structure, the sizeof() is different before and after char is int. The specific reason is not clear, so write it down for the time being. But if you add #pragma pack(push,1) and pragma pack(pop), this problem will not occur.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326356978&siteId=291194637