0

I want to pass a variable by parameter and then allocated a memory region using malloc to that parameter. Actually, I know how to do that, but I was wondering why this function does not work as I expected:

void temp1(int *a) {
    int *b = (int*) malloc(sizeof(int));
    a = b; // a receives the pointer from b, only while it's in temp1 function;
}

while this function works:

void temp2(int **a) {
    int *b = (int*) malloc(sizeof(int));
    *a = b;
}

when calling this way from main:

int main()
    int *t1 = NULL;
    temp1(t1); // but after exiting the temp1 function the t1 value is still NULL

    int *t2;
    temp2(&t2); // this works 

    return 0;
}

So, what I'm missing in the function temp1 that avoids it to work? Is it because in function temp1 I'm trying to change the content of the parameter int *a? I mean, when I do a = b; in temp1 the a holds only a copy of the address that I wanted to assign to t1?

Daniel Bonetti
  • 2,306
  • 2
  • 24
  • 33

0 Answers0