How can I pass a reference to a character pointer to a function and return the value back?

In this code, I passed a link to a character pointer to the test function and in the functional test I malloc size and write the data to this address, after which I print it and get a zero value.

#include <stdio.h> #include <stdlib.h> void test(char*); int main() { char *c=NULL ; test(c); printf("After test string is %s\n",c); return 0; } void test(char *a) { a = (char*)malloc(sizeof(char) * 6); a = "test"; printf("Inside test string is %s\n",a); } 

output:

 Inside test string is test After test string is (null) 
+4
source share
2 answers

You cannot just pass a pointer. Instead, you need to pass the address of the pointer. Try the following:

 void test(char**); int main() { char *c=NULL ; test(&c); printf("After test string is %s\n",c); free(c); // Don't forget to free it! return 0; } void test(char **a) { *a = (char*)malloc(sizeof(char) * 6); strcpy(*a,"test"); // Can't assign strings like that. You need to copy it. printf("Inside test string is %s\n",*a); } 

The rationale is that the pointer is passed by value. This means that it is copied to the function. Then you overwrite the local copy inside the function with malloc.

So, to get around this, you need to pass the address of the pointer.

+13
source

Hey sam you passed char c pointer in code

  test(c); 

but where you need to send the address of the charecter variable.

  test(&c); 

This makes a difference in your code here, so just try this change in your code and execute it.

0
source

Source: https://habr.com/ru/post/1379428/


All Articles