【问题标题】:changing a string in a function更改函数中的字符串
【发布时间】:2013-12-08 13:32:53
【问题描述】:

如果我有这种函数:str1= NULL 开头

 Result dosomething(char* str1, char* str){
    str1=malloc(strlen(str2)+1); //followed by NULL check
    strcpy(str1, str2);
    .
    .
 return something

然后我在其他一些函数中使用这个函数:

 char* output="hello";
 char* input=NULL;
 result=dosomething(input,output);

由于某种原因,使用“dosomething”函数后输入仍然为 NULL,尽管如果我在 strcpy 之后立即使用 printf,我可以看到 str1 确实更改为“hello”。将它们传递给其他函数时,我在这里对 char* 做错了吗?

【问题讨论】:

  • 在 C 中,函数参数是按值传递的。也就是说,它们被复制了。现在重新考虑您希望您的代码做什么,它做什么,并考虑为什么(并搜索重复,因为它们有很多)。

标签: c string function pointers


【解决方案1】:

您需要传递一个指向要更改的字符串的指针

Result dosomething(char** str1, char* str){
    *str1=malloc(strlen(str2)+1); //followed by NULL check
    strcpy(*str1, str2);

调用

result=dosomething(&input,output);

或者改函数返回新分配的字符串,返回NULL表示错误

char* dosomething(char* str){
    char* str1=malloc(strlen(str2)+1); //followed by NULL check
    strcpy(str1, str2);
    ...
    return str1;

调用

input=dosomething(output);
if (input==NULL) {
    // error

【讨论】:

  • 我试过了,结果一样。但是如果我错了请纠正我,但是 char* 本身就是一个指针,所以无论哪种方式我都在传递一个指针并且它应该改变,为什么要传递一个指向指针的指针?
  • @littlerunaway 因为只传递一个指针可以帮助改变指针指向的对象。指针不是魔术,它只是一个指针。 思考。
  • @littlerunaway 字符串是char*。这是按值传递给dosomething。您可以更改它在dosomething 中指向的内存的内容,但不能更改它指向的内存。要更改它指向的内存,您需要传递一个指向字符串的指针,即 char**
  • 但这不是我想要做的吗?改变指针指向的对象?
  • 是的,这正是您想要做的。您不能将char* 参数传递给doSomething。您可以通过我的回答中列出的任何一种方式进行操作。
【解决方案2】:

通过指针传递字符串

Result dosomething(char** str1, char* str){
    *str1=malloc(strlen(str2)+1); //followed by NULL check
    strcpy(*str1, str2);

并用作

result=dosomething(&input,output);

由于你需要修改指针的值,所以传递它的地址。

【讨论】:

    【解决方案3】:

    你被绊倒了,因为你正在改变你在函数内部传递的指针的值。为了便于说明,请将此处的 char* 替换为 int 以查看问题所在:

    Result dosomething_int(int a, int b) {
        a = 29;
        ...
    }
    

    这里29 代替了您的malloc 调用,它将您传递的str1 指针的值替换为一个新值。现在使用这个函数:

    int output = 17;
    int intput = 0;
    result = dosomething_int(input,output);
    

    您希望input 的值在此之后是 0 还是 29?或许您可以轻松回答这个问题——char * 案例中也发生了同样的事情。您需要将指针传递给您的 char * 来解决它:

    Result dosomething(char** str1, char * str2) {
        *str1 = malloc(...);
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-09
      • 2020-04-18
      • 2019-12-24
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 2012-10-23
      相关资源
      最近更新 更多