C/C++中的对象/结构对齐

Ale*_*lex 1 c++ g++

#include <iostream>

using namespace std;

struct test
{
    int i;
    double h;
    int j;
};

int main()
{
    test te;
    te.i = 5;
    te.h = 6.5;
    te.j = 10;

    cout << "size of an int: " << sizeof(int) << endl; // Should be 4
    cout << "size of a double: " << sizeof(double) << endl; //Should be 8
    cout << "size of test: " << sizeof(test) << endl; // Should be 24 (word size of 8 for double)

    //These two should be the same
    cout << "start address of the object: " << &te << endl; 
    cout << "address of i member: " << &te.i << endl;

    //These two should be the same
    cout << "start address of the double field: " << &te.h << endl;
    cout << "calculate the offset of the double field: " << (&te + sizeof(double)) << endl; //NOT THE SAME

    return 0;    
}
Run Code Online (Sandbox Code Playgroud)

输出:

size of an int: 4
size of a double: 8
size of test: 24
start address of the object: 0x7fffb9fd44e0
address of i member: 0x7fffb9fd44e0
start address of the double field: 0x7fffb9fd44e8
calculate the offset of the double field: 0x7fffb9fd45a0
Run Code Online (Sandbox Code Playgroud)

为什么最后两行产生不同的值?我用指针算法做错了什么?

Pio*_*zmo 8

(&te + sizeof(double))
Run Code Online (Sandbox Code Playgroud)

这与:

&((&te)[sizeof(double)])
Run Code Online (Sandbox Code Playgroud)

你应该做:

(char*)(&te) + sizeof(int)
Run Code Online (Sandbox Code Playgroud)