Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char * as a reference in C

Tags:

c

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);
like image 327
deem Avatar asked Apr 11 '12 13:04

deem


People also ask

What does char * mean in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.

How to send char array to function in c++?

How Arrays are Passed to Functions in C/C++? A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().


1 Answers

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);
like image 174
MByD Avatar answered Nov 02 '22 23:11

MByD