9

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)
T.Rob
  • 31,522
  • 9
  • 59
  • 103
sam_k
  • 5,983
  • 14
  • 76
  • 110

2 Answers2

20

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.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
0

HeY Sam you have passed the char pointer c in code

 test(c);

but where as you have to send the Address of the charecter variable.

 test(&c);

Here this makes an differece in your code so just try this change in your code and execute it.

Gouse Shaik
  • 340
  • 1
  • 2
  • 15