char *作为C中的参考

时间:2012-04-11 13:49:23

标签: c

如何传递像char *这样的参数作为参考?

我的函数使用malloc()

void set(char *buf)
{
    buf = malloc(4*sizeof(char));
    buf = "test";
}

char *str;
set(str);
puts(str);

6 个答案:

答案 0 :(得分:18)

您传递指针的地址:

void set(char **buf)
{
    *buf = malloc(5*sizeof(char));
    // 1. don't assign the other string, copy it to the pointer, to avoid memory leaks, using string literal etc.
    // 2. you need to allocate a byte for the null terminator as well
    strcpy(*buf, "test");
}

char *str;
set(&str);
puts(str);

答案 1 :(得分:5)

您必须将其作为指针传递给指针:

void set(char **buf)
{
    *buf = malloc(5 * sizeof(char));
    strcpy(*buf, "test");
}

这样称呼:

char *str;
set(&str);
puts(str);
free(str);

请注意,我已更改malloc调用以分配五个字符,这是因为您只为实际字符分配,但字符串还包含一个特殊的终结符字符,您也需要空间。

我还使用strcpy将字符串复制到分配的内存中。这是因为你覆盖了指针,否则意味着你松开了你分配的指针并且会有内存泄漏。

当你完成指针时,你还应该记住free指针,或者在程序结束之前内存将保持分配状态。

答案 2 :(得分:4)

C不支持按引用传递。但是你可以将指针传递给你的指针,然后设置:

void set(char **buf)
{
    *buf = malloc(5*sizeof(char)); //5, to make room for the 0 terminator
    strcpy(*buf,"test"); //copy the string into the allocated buffer.
}

char *str;
set(&str);
puts(str);

答案 3 :(得分:3)

您要将指针传递给指针char**:C中没有引用。

void set(char** buf)
{
    *buf = malloc(5); /* 5, not 4: one for null terminator. */
    strcpy(buf, "test");
}

请注意:

buf = "test";

不会将"test"复制到buf,而是将buf指向字符串文字"test"的地址。复制使用strcpy()

请记住,当不再需要时,free()返回缓冲区:

char* str;
set(&str);
puts(str);
free(str);

答案 4 :(得分:1)

C是按值传递。没有传递参考。

答案 5 :(得分:-1)

C不能通过引用传递函数参数,C总是按值传递它们。

来自Kernighan&里奇:

  

(K& R 2nd,1.8 Call by value)“在C中,所有函数参数都通过”value“传递”

要修改指向T的指针,可以指向指向T的指针作为函数参数类型。