char * 作为 C 中的引用

标签 c

如何传递参数如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/

相关文章:

c - 在指针中填充 -1 作为特殊值

c - 如何用其他字符替换字符串中的特定字符

c - malloc 上已释放对象的校验和不正确

c - 资源获取和pthreads

c - 为什么这段 C 代码会崩溃

c - 如何实现用户空间多线程虚拟机,例如Erlang运行时

c - 如何从 C 中的 Linux 终端中删除一个字符

c - 具有多个条件的 if 的执行顺序

c - "(int)"中的 "sizeof (int)"是类型转换运算符还是某些特殊情况参数? [C]

C程序的困惑输出