简体   繁体   English

c ++将char数组传递给函数并进行更改

[英]c++ pass char array to function and change it

I try to make a function that can change the content of a specified char array 我尝试创建一个可以更改指定char数组内容的函数

void change_array(char *target)
{
    target="hi";
}

int main()
{
    char *a[2];
    change_array(a[1]);
    cout<<*(a[1]);
}

But then the content of a[1] stays at 0x0(void) 但是[1]的内容保持在0x0(无效)

First, your function has a copy of the pointer passed to it, so there is no effect seen on the caller side. 首先,你的函数有一个传递给它的指针的副本,所以在调用方没有看到效果。 If you want to modify the function argument, pass a reference: 如果要修改函数参数,请传递引用:

void change_array(char*& target) { ... }
//                     ^

Second, you cannot/should not bind a non-const pointer to a string literal. 其次,你不能/不应该将非const指针绑定到字符串文字。 Use const char* instead. 请改用const char*

void change_array(const char*& target) { ... }
//                ^^^^^      ^

int main()
{
    const char* a[2];
    change_array(a[1]);
    cout<<*(a[1]);
}

When you pass an argument to a function, it's normally passed by value, meaning its value is copied. 将参数传递给函数时,它通常按值传递,这意味着它的值被复制。 If you want to change it you have to pass it by reference. 如果你想改变它,你必须通过引用传递它。 The same goes for pointers, if you want to change a pointer then you need to pass it by reference as well: 对于指针也是如此,如果你想更改指针,那么你也需要通过引用传递它:

void change_array(const char*& target) { ... }

You need to pass it as a reference: 您需要将其作为参考传递:

void change_array(char*&target)
{
    target="hi";
}

Otherwise, you will just change the local copy of target , which won't make any difference to the value outside of the function. 否则,您只需更改target的本地副本,这不会对函数外部的值产生任何影响。

Try this design instead: 请尝试此设计:

std::string get_string()
{
    return "hi";
}

int main()
{
    std::string a[2];
    a[1] = get_string();
    std::cout<< a[1];
}

Salient points: 突出点:

  • return by value 按价值返回
  • use std::string 使用std :: string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM