我在函数中递增指针但在退出函数后返回到先前的位置

nic*_*day 0 c++

#include <iostream>
using namespace std;
void func (char *data)
{
    data+=3;
    cout << data << "\n"; //456789
}

int main() {
    // your code goes here
    char * str = "123456789";
    char *data = str;
    func(data);
    cout << data << "\n"; // 123456789
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?无法理解它是如何可能的.你能解释一下吗?

Som*_*ude 6

将变量传递给函数时,它们按值传递,这意味着变量的值被复制到参数变量.由于您只修改了函数中的副本,因此不会修改原始变量.

To pass the actual original value you need to pass it by reference. This is done by using the ampersand when declaring the argument:

void func (char *&data)
Run Code Online (Sandbox Code Playgroud)

  • 你的答案比我的好.最初,你(像我之后)陷入了像C一样思考的陷阱,但这就是C++.布拉沃.:) (2认同)