Double Pointers in C and their scope -


i have code:

void alloc2(int** p) {    *p = (int*)malloc(sizeof(int));    **p = 10; }  void alloc1(int* p) {    p = (int*)malloc(sizeof(int));    *p = 10; }  int main(){    int *p;    alloc1(p);    //printf("%d ",*p);//value undefined    alloc2(&p);    printf("%d ",*p);//will print 10    free(p);    return 0; } 

so, understand alloc1 makes local copy it's not effecting outside function pointer given parameter.

but happening alloc2?

tl;dr;

and why alloc1(&p); won't work?

update

i think answered question. crucial thing & makes pointer , a built double pointer bei dereferencing once. double pointer points address given malloc. address filled 10.

and alloc1(&p); work, couldn't derefence double pointer since takes single pointer.

thanks of you

it clearer if gave variables in different functions different names. since have multiple variables , arguments named p, , distinct each other, easy confuse yourself.

void alloc2(int** pa2) {      *pa2 = (int*)malloc(sizeof(int));      **pa2 = 10; }  void alloc1(int* pa1)  {     pa1 = (int*)malloc(sizeof(int));     *pa1 = 10; }  int main() {     int *p = 0;     alloc1(p);     //printf("%d ",*p);//value undefined     alloc2(&p);     printf("%d ",*p);//will print 10     free(p);     return 0; } 

apart renaming arguments of functions, i've initialised p in main() 0 (the null pointer). had uninitialised, means accessing value (to pass alloc1()) gives undefined behaviour.

with p being null, alloc1() receives null pointer value of pa1. local copy of value of p main(). malloc() call changes value of pa1 (and has no effect on p in main(), since different variable). statement *pa1 = 10 sets malloced int 10. since pa1 local alloc1() ceases exist when alloc1() returns. memory returned malloc() not free()d though (pa1 ceases exist, points doesn't) result memory leak. when control passes main(), value of p still 0 (null).

the call of alloc2() different, since main() passes address of p. value of pa2 in alloc2(). *pa2 = (int *)malloc(sizeof(int)) statement change value of p in main() - value returned malloc(). statement **pa2 = 10 changes dynamically allocated int 10.

note (int *) on result of malloc() unnecessary in c. if need it, means 1 of

  1. you have not done #include <stdlib.h>. type conversion forces code compile, usage of int - strictly speaking - gives undefined behaviour. if case, remove int * , add #include <stdlib.h>.
  2. you compiling c code using c++ compiler.

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -