c++ - 简单的指针问题(我不知道为什么我没有得到确切的解释)

标签 c++

这个例子看起来很简单,我不知道为什么我不知道确切的解释..

在下面的例子中:

#include <cstdio>

void scan(char* p){
  printf("%c", *p++);
}

int main() {
  char str[] = "hi this is a test";
  char* p = str;

  while(*p != '\0'){
    printf("%c", *p++); //ok..
  // scan(p); //crash
  }

}

使用扫描功能有什么问题。即,如果这甚至是问题所在,为什么 p 在外层没有增加?

最佳答案

ie why does p not get incremented in the outer level if that is even the problem?

您的函数在该指针的拷贝上运行,因此递增不会影响原始指针。

要实现通过引用传递该指针变量:

void scan(char*& p){
  printf("%c", *p++);
}

这是一个 working example online .

关于c++ - 简单的指针问题(我不知道为什么我没有得到确切的解释),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730153/

相关文章:

C++检测模板类

c++ - friend 关键字(类/函数)如何打破 C++ 中的封装?

c++ - 包含两个函数名称相同的库时出现链接器警告 "second definition ignored"

c++ - Visual Studio 2012 C++ 使用 Boost Signal2 编译错误

c++ - 如何从 std::istream 加载 wxXmlDocument?

c++ - 向上转换空指针是否会导致未定义的行为

c++ - 将从不可复制派生的对象放置到 vector 中

c++ - 覆盖 new 但告诉 unordered_map 不要使用它

c++ - 检查浮点参数是否正确

c++ - 在开关盒中返回 bool 值