Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass character pointer reference to function and get affected value back?

Tags:

c

pointers

In this code I passed a character pointer reference to function test and in function test I malloc size and write data to that address and after this I print it and got null 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)
like image 922
sam_k Avatar asked Nov 03 '11 06:11

sam_k


1 Answers

You can't just pass the pointer in. You need to pass the address of the pointer instead. Try this:

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 reasoning is that the pointer is passed by value. Meaning that it gets copied into the function. Then you overwrite the local copy within the function with the malloc.

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

like image 168
Mysticial Avatar answered Oct 26 '22 10:10

Mysticial