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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With