我的代码:
#include <iostream>
using namespace std;
int main() {
char *test = (char*)malloc(sizeof(char)*9);
test = "testArry";
cout << &test << " | " << test << endl;
test++;
cout << &test << " | " << test << endl;
return 1;
}
结果:
004FF804 | testArry
004FF804 | estArry
我不明白为什么我移动了我的数组指针而地址却没有改变。
最佳答案
指针确实改变了。你只是不打印它。打印指针 test
:
cout << (void*) test << endl;
&test
是 test
所在的内存位置已存储。
test
是您用 test++
递增的值(即,您没有增加 &test
)。
当你做 cout << test
operator<<
的过载被选中的是需要 const char*
的那个并将其视为 C 风格的字符串,打印它指向的字符。投给void*
避免此行为以打印 test
的实际值, 而不是它指向的值。
关于c++ - 移动数组指针不会改变起始地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42609057/