C++ 中的指针、sizeof() 和地址

Pointers, sizeof() and address in C++

这是程序

int main() {   
    cout << sizeof(int) << endl;        // for int its 4 in g++ compiler

    int *p;
    int a = 5;
    p = &a;
    cout << "The value of p is: " << p << endl;
    cout << "The value of p + integer is: " << p + 0 << endl;

    // lets take the size of individual 1, 2, 3
    cout << "The sizeof(0) is: " << sizeof(0) << endl;   // 4
    cout << "The sizeof(1) is: " << sizeof(1) << endl;   // 4
    cout << "The sizeof(2) is: " << sizeof(2) << endl;   // 4

    cout << "The value of p + 0 is: " << p + 0 << endl;
    cout << "The value of p + 1 is: " << p + 1 << endl;
    cout << "The value of p + 2 is: " << p + 2 << endl;

    return 0;
}

C++ 中的 sizeof() 函数在 g++ 编译器中给出 sizeof(int) 4 个字节。所以我将 sizeof(1)sizeof(2)sizeof(0) 打印到终端,我得到了 4 个字节。

所以我在上面的程序中尝试了一些指针运算link。我将 1 添加到指针变量。假设 int *p; int a = 10;。现在我分配了p = &a;。现在当我打印 p 时它给出 0x24fe04 而当我打印 p + 0 时它是一样的。但是当我尝试添加 p + 1p + 2 时,它会给出不同的输出,如下所示:分别为 0x24fe080x24fe0c。请帮助我理解这个算术。为什么 p+1p+2 不等于地址,因为它贡献了相同的 4 个字节。

指针就是这样,它指向另一个内存区域。

int a = 3; 
int *p = &a;
++a;
std::cout << p << std::endl;    
std::cout << *p << std::endl;
std::cout << &p << std::endl;
std::cout << &a << std::endl;

应该输出:

The address of a
4
The address of p
The address of a

如果您执行 p+1,您将在内存堆栈中从 a 的地址向上移动 4 个字节,因为在 32 位机器上内存被索引到该对齐方式。在 64 位机器上,它有两倍的对齐方式,因此由于内存索引差异,您不能混合使用 32 位和 64 位代码。

你也有指针指针,所以你可以操纵指针

int **pp = &p
std::cout << *pp; // = 4 = p = a

编辑

应该检查一下,我的错误,我已经解决了上面的问题,感谢 Benjamin Lindley

当你说p + 1时,意思就是p + 1 * sizeof(int)。正如我提到的 here,公式是

                                 =  +  × 

这就是为什么您在尝试 p + 0 时获得 0x24fe04,并在 p + 1

时获得 0x24fe08