9

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

我的函数使用 malloc()

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

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

6 回答 6

19

您传递指针的地址:

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);
于 2012-04-11T13:50:52.140 回答
5

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

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

像这样称呼它:

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

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

我还使用strcpy将字符串复制到分配的内存。那是因为否则您将覆盖指针,这意味着您会丢失分配的指针并且会发生内存泄漏。

完成后还应该记住free指针,否则内存将一直分配到程序结束。

于 2012-04-11T13:51:10.577 回答
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);
于 2012-04-11T13:51:24.877 回答
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);
于 2012-04-11T13:51:32.030 回答
1

C 是按值传递。没有传递引用。

于 2012-04-11T13:50:41.860 回答
0

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

来自 Kernighan & Ritchie:

(K&R 2nd,1.8 按值调用)“在 C 中,所有函数参数都由“值”传递”

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

于 2012-04-11T13:53:54.387 回答