输出数组成员的连续地址

Căt*_*rbu 0 c++ arrays memory-address

在此处输入图片说明

我画这个是为了更好地理解。在 PC 的内存中有连续的内存区域,长度为 1 个字节(绿色区域)。它们可以分组以表示更大的数据(如int我们的示例中的an )。

我想添加到这张图片中的是,绿色方块是连续的地址,如0x000000后跟0x000001等。然后地址从arr四跳,0x000000下一个将是0x000004(因为int在这方面是4bytes)。

代码_1

int arr[4] = {1,2,3,4};

int *p = arr;

cout << p << endl;
cout << ++p << endl;
cout << ++p << endl;
cout << ++p << endl;
Run Code Online (Sandbox Code Playgroud)

输出_1

0x69fedc
0x69fee0
0x69fee4
0x69fee8
Run Code Online (Sandbox Code Playgroud)

代码_2

char arrr[5] = {'1','2','3','4', '\n'};

char *ptr = arrr;

cout << &ptr << endl;
cout << &(++ptr) << endl;
cout << &(++ptr) << endl;
cout << &(++ptr) << endl;
Run Code Online (Sandbox Code Playgroud)

输出_2

0x69fed0
0x69fed0
0x69fed0
0x69fed0
Run Code Online (Sandbox Code Playgroud)

问题:我希望output_2地址是0x69fed0, 0x69fed1, 0x69fed2,0x69fed4

efe*_*ion 5

这是因为您正在显示指针的地址而不是存储在指针中的地址:

char *ptr = 0;
std::cout << &ptr;       // address where the pointer is placed
std::cout << (void*)ptr; // address managed by the pointer = 0

++ptr;

std::cout << &ptr;       // this value never changes
std::cout << (void*)ptr; // Now this value should be 1
Run Code Online (Sandbox Code Playgroud)

  • @CătălinaSîrbu `void*` 是一个匿名指针。当使用“char*”打印指针*内部*的文本时,“cout”有一个重载,但是当使用“void*”时,将打印地址 (2认同)