char * as a reference in C

c

Solution

You pass the address of the pointer:

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);

Problem

How to pass the param like char * as a reference? My function uses malloc() ``` void set(char *buf) { buf = malloc(4*sizeof(char)); buf = "test"; } char *str; set(str); puts(str); ```

Original source