Char * as a reference in C

How to pass parameter as 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); 
+7
source share
6 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); 
+17
source

You should pass it as a pointer to a pointer:

 void set(char **buf) { *buf = malloc(5 * sizeof(char)); strcpy(*buf, "test"); } 

Name it as follows:

 char *str; set(&str); puts(str); free(str); 

Note that I changed the call to malloc to highlight five characters, because you only select the actual characters, but the line also contains a special terminator character, and you also need a place for that.

I also use strcpy to copy the string to the allocated memory. This is because you rewrite the pointer differently, that is, you lose the pointer that you select and will have a memory leak.

You should also remember the free pointer when you finish with it, or the memory will remain allocated until the program ends.

+5
source

C does not support passing by reference. But you can pass a pointer to a pointer and set the following:

 void set(char **buf) { *buf = malloc(5*sizeof(char)); //5, to make room for the 0 terminator strcpy(*buf,"test"); //copy the string into the allocated buffer. } char *str; set(&str); puts(str); 
+4
source

You must pass a pointer to a pointer, char** : there are no references in C.

 void set(char** buf) { *buf = malloc(5); /* 5, not 4: one for null terminator. */ strcpy(buf, "test"); } 

Note that:

 buf = "test"; 

does not copy "test" to buf , but points buf to the address of the string literal "test" . To copy using strcpy() .

Remember the free() buffer returned if it is no longer needed:

 char* str; set(&str); puts(str); free(str); 
+3
source

C is a pass by value. No missing links.

+1
source

C cannot pass arguments to a function by reference; C always passes them by value.

From Kernigan and Richie:

(K & R 2nd, 1.8 Call by value) "In C, all function arguments are passed by value" "

To change a pointer to T , you can specify a pointer to T as a type of function argument.

-one
source

All Articles