this doesn't work:
void function(char* var)
{
var = (char*) malloc (100);
}
int main()
{
char* str;
function(str);
strcpy(str, "some random string");
printf("%s\n", str);
return 0;
}
this does:
void function(char* var)
{
//var = (char*) malloc (100);
}
int main()
{
char* str;
//function(str);
str = (char*) malloc (100);
strcpy(str, "some random string");
printf("%s\n", str);
return 0;
}
Why?
You have to pass the address of the pointer to assign the address you want inside the function, otherwise you are just passing a copy of it:
void function(char** var)
{
*var = malloc (100);
}
int main()
{
char* str;
function(&str);
strcpy(str, "some random string");
printf("%s\n", str);
return 0;
}
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