passing a pointer to a pointer

Hi all,

I am still trying to understand pointer to a pointer better. I understand that when you want to change the value of a pointer when passing to a function, you must pass a pointer to that pointer, hence something like :
1
2
3
4
5
6
7
8
9
10
11
12
void ptop (int ** i)
{
	(*i) = 10;
}

int main()
{
	int * i;
	ptop(&i);
        printf("i = %d", i);
	return 0;
}


This will print i = 10. However, why is it that when I do this,
1
2
3
4
void ptop (int * i)
{
	(*i) = 10;
}

basically (int * a) instead of (int ** a) as the parameter, it also prints i = 10?
Also when I pass an array as a parameter,
1
2
3
4
5
6
7
8
9
10
11
12
void array (int arr[])
{
	arr[0] = 20;
}

int main()
{
	arr[2] = {0, 0);
	array(arr);
        printf("arr[0] = %d", arr[0]);
	return 0;
}


the value of the array gets updated to 20? I thought it only gets a copy of arr and should not update its value?
Any explanations to clarify my understand would be appreciated.
Thanks a bunch!
Last edited on
Hi jameric,

when calling ptop(&i), you pass the address of the variable i (it does not matter that i is a pointer, too). Within ptop, the assignment (*i) = 10 dereferences this pointer, so you are setting the variable i (from main!) to 10, not the value i points to. If you now output i, the result will of course be 10.

In a nutshell, you are manipulating manipulating the variable i (from main) the whole time, and not the value i points to. If you try to dereference i, you should get a segfault.
Last edited on
Topic archived. No new replies allowed.