如何传递参数如char *作为引用?
我的函数使用 malloc()
void set(char *buf)
{
buf = malloc(4*sizeof(char));
buf = "test";
}
char *str;
set(str);
puts(str);
最佳答案
你传递指针的地址:
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);
关于char * 作为 C 中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10107292/