输出数组成员的连续地址
Outputting succesive addresses of members of arrays
我画这个是为了更好地理解。在 PC 的内存中有连续的长度为 1 字节的内存区域(绿色的)。它们可以分组以表示更大的数据(在我们的示例中为 int
)。
我想添加到这张图片的是,绿色方块是连续的地址,如 0x000000
后跟 0x000001
等。然后 arr
的地址跳跃了四个,如0x000000
下一个是 0x000004
(因为这里的 int
是 4bytes
)。
code_1:
int arr[4] = {1,2,3,4};
int *p = arr;
cout << p << endl;
cout << ++p << endl;
cout << ++p << endl;
cout << ++p << endl;
output_1:
0x69fedc
0x69fee0
0x69fee4
0x69fee8
code_2:
char arrr[5] = {'1','2','3','4', '\n'};
char *ptr = arrr;
cout << &ptr << endl;
cout << &(++ptr) << endl;
cout << &(++ptr) << endl;
cout << &(++ptr) << endl;
output_2:
0x69fed0
0x69fed0
0x69fed0
0x69fed0
问题:我希望在 output_2
中,我希望地址为 0x69fed0
、0x69fed1
、0x69fed2
,0x69fed4
这是因为您显示的是指针的地址,而不是指针中存储的地址:
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
我画这个是为了更好地理解。在 PC 的内存中有连续的长度为 1 字节的内存区域(绿色的)。它们可以分组以表示更大的数据(在我们的示例中为 int
)。
我想添加到这张图片的是,绿色方块是连续的地址,如 0x000000
后跟 0x000001
等。然后 arr
的地址跳跃了四个,如0x000000
下一个是 0x000004
(因为这里的 int
是 4bytes
)。
code_1:
int arr[4] = {1,2,3,4};
int *p = arr;
cout << p << endl;
cout << ++p << endl;
cout << ++p << endl;
cout << ++p << endl;
output_1:
0x69fedc
0x69fee0
0x69fee4
0x69fee8
code_2:
char arrr[5] = {'1','2','3','4', '\n'};
char *ptr = arrr;
cout << &ptr << endl;
cout << &(++ptr) << endl;
cout << &(++ptr) << endl;
cout << &(++ptr) << endl;
output_2:
0x69fed0
0x69fed0
0x69fed0
0x69fed0
问题:我希望在 output_2
中,我希望地址为 0x69fed0
、0x69fed1
、0x69fed2
,0x69fed4
这是因为您显示的是指针的地址,而不是指针中存储的地址:
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