c++ - 移动数组指针不会改变起始地址

标签 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;
}

结果:

004FF804 | testArry
004FF804 | estArry

我不明白为什么我移动了我的数组指针而地址却没有改变。

最佳答案

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

cout << (void*) test << endl;

&testtest 所在的内存位置已存储。
test是您用 test++ 递增的值(即,您没有增加 &test )。

当你做 cout << test operator<< 的过载被选中的是需要 const char* 的那个并将其视为 C 风格的字符串,打印它指向的字符。投给void*避免此行为以打印 test 的实际值, 而不是它指向的值。

关于c++ - 移动数组指针不会改变起始地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42609057/

相关文章:

java - 使用 Streams 映射到二维数组

java - 使用 super.toString 将 String 和 int 添加到父类中

c++ - QFile 打不开

java - 编辑默认部分并制作一组按钮

java - 自动填充多维 String[][] 数组

c++ - C字符串和C++字符串有什么区别?

asp.net - Server.Htmlencode 性能与 Regex.Replace 与 String.Replace 的比较

c++ - Libcpmt.lib:为 'RuntimeLibrary'检测到错误LNK2038不匹配:值 'MT_StaticRelease'与值 'MD_DynamicRelease'不匹配

c++ - 带有 VS 2015 命令提示符的 Visual Studio 2017 + vcvarsall 无效 + 找不到 nmake

c++ - 如何通过 gdb 调试 nodejs 插件