Simple c malloc

c, malloc

Solution

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;
}

Problem

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?

Original source

Related problems