一个关于struct字节对齐的问题
struct STUDENT{
char name[10];
char sex;
int age;
char grade[10];
};
对于如上结构体。vc6.0下sizeof()的结果是28,我跟踪看内存中name和sex一起时12字节,age4字节,grade12字节,为什么内存中是这么放呢?
#include <stdio.h> #define BYTE_WIDTH 8 struct STUDENT { char name[10]; char sex; int age; char grade[10]; }; char * to_binary_string(char ch, char * str) { int i, j; for(i = BYTE_WIDTH - 1, j = 0; i > -1; i--, j++) str[j] = ((ch >> i) & 1) + '0'; str[j] = '\0'; return str; } int main() { struct STUDENT john = {"john", 'l', 16, "v1"}; char * p1 = (char *)&john, * p2 = p1; char str[BYTE_WIDTH + 1]; while(p1 < p2 + sizeof(john)) { printf("%p: %s\n", p1, to_binary_string(*(char *)p1, str)); p1++; } return 0; } /* Output: 0022FEEC: 01101010 0022FEED: 01101111 0022FEEE: 01101000 0022FEEF: 01101110 0022FEF0: 00000000 0022FEF1: 00000000 0022FEF2: 00000000 0022FEF3: 00000000 0022FEF4: 00000000 0022FEF5: 00000000 0022FEF6: 01101100 0022FEF7: 00000000 0022FEF8: 00010000 0022FEF9: 00000000 0022FEFA: 00000000 0022FEFB: 00000000 0022FEFC: 01110110 0022FEFD: 00110001 0022FEFE: 00000000 0022FEFF: 00000000 0022FF00: 00000000 0022FF01: 00000000 0022FF02: 00000000 0022FF03: 00000000 0022FF04: 00000000 0022FF05: 00000000 0022FF06: 00000000 0022FF07: 00000000 Process returned 0 (0x0) execution time : 0.040 s Press any key to continue. */
#include <iostream> #include <cstring> #define BYTE_WIDTH 8 class Student { private: char name[10]; char sex; int age; char grade[10]; public: Student() { using std::strcpy; strcpy(name, "john"); sex = 'l'; age = 16; strcpy(grade, "v1"); } ~Student() {} char * to_binary_string(int offset, char * str) { char * p = (char *)this + offset; for(int i = BYTE_WIDTH - 1, j = 0; i > -1; i--, j++) str[j] = ((*p >> i) & 1) + '0'; str[BYTE_WIDTH] = '\0'; return str; } }; int main() { using std::cout; using std::endl; Student john; char str[BYTE_WIDTH + 1], * p = (char *)&john; cout << "sizeof(Student) : " << sizeof(Student) << endl; for(int i = 0; i < sizeof(john); i++) cout << (void *)p << ": " << john.to_binary_string(i, str) << endl; return 0; } /* Output: sizeof(Student) : 28 0x22feec: 01101010 0x22feec: 01101111 0x22feec: 01101000 0x22feec: 01101110 0x22feec: 00000000 0x22feec: 10001100 0x22feec: 11111011 0x22feec: 01110101 0x22feec: 11110100 0x22feec: 11010110 0x22feec: 01101100 0x22feec: 10000001 0x22feec: 00010000 0x22feec: 00000000 0x22feec: 00000000 0x22feec: 00000000 0x22feec: 01110110 0x22feec: 00110001 0x22feec: 00000000 0x22feec: 01110101 0x22feec: 10111100 0x22feec: 01011011 0x22feec: 11111111 0x22feec: 01110101 0x22feec: 01010000 0x22feec: 00110100 0x22feec: 01000001 0x22feec: 00000000 Process returned 0 (0x0) execution time : 0.078 s Press any key to continue. */