double pointer assignment

I am having trouble understanding why we need double pointer assignment. I looked at this link
http://stackoverflow.com/questions/5580761/why-use-double-pointer-or-why-use-pointers-to-pointers

Why will this code not work? Why will we lose the reference to memory allocated in alloc1?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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); ///// WHY CANNOT I DO THIS HERE? 
   //printf("%d ",*p);//value is undefined
   alloc2(&p);
   printf("%d ",*p);//will print 10
   free(p);
   return 0;
}
Last edited on

Because for a return value via the argument list you need to pass the address of the variable. The variable you are wanting returned is a pointer, hence the double pointer notation.
Topic archived. No new replies allowed.