移动数组指针不会更改启动的ADDRESS

Yas*_*Yas 4 c++ arrays string pointers

我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

结果:

004FF804 | testArry
004FF804 | estArry
Run Code Online (Sandbox Code Playgroud)

我不明白我是如何移动我的数组指针和地址没有改变的.

eml*_*lai 9

指针确实改变了.你只是不打印它.要打印指针test:

cout << (void*) test << endl;
Run Code Online (Sandbox Code Playgroud)

&test是存储的内存位置test.
test是您增加的值test++(即,您没有增加&test).

当你做cout << test的时候,operator<<那个被选中的重载就是一个const char*把它当作C风格的字符串处理,打印它所指向的字符.转换为void*避免此行为以打印实际值test,而不是它指向的值.

  • <pedantic>说出为什么演员表演`(void*)`</ pedantic>可能是一个好主意 (2认同)