如何传递像char*这样的参数作为参考?
我的函数使用malloc()
void set(char *buf)
{
buf = malloc(4*sizeof(char));
buf = "test";
}
char *str;
set(str);
puts(str);
Run Code Online (Sandbox Code Playgroud)
MBy*_*ByD 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);
Run Code Online (Sandbox Code Playgroud)
你必须将它作为指针传递给指针:
void set(char **buf)
{
*buf = malloc(5 * sizeof(char));
strcpy(*buf, "test");
}
Run Code Online (Sandbox Code Playgroud)
像这样称呼它:
char *str;
set(&str);
puts(str);
free(str);
Run Code Online (Sandbox Code Playgroud)
请注意,我已将更改malloc调用更改为分配五个字符,这是因为您只为实际字符分配,但字符串还包含一个特殊的终结符字符,您也需要空间.
我还strcpy用来将字符串复制到分配的内存中.这是因为否则你会覆盖指针,这意味着你松开了你分配的指针并且会有内存泄漏.
free当你完成它时你也应该记住指针,或者在程序结束之前内存将保持分配状态.