#include <stdlib.h>
int malloc2(int **a) {
*a = malloc(sizeof (int));
return 0;
}
int main() {
int* b = NULL;
malloc2(&b);
}
If an argument only accepts double pointers, how can it accept an address value?
#include <stdlib.h>
int malloc2(int **a) {
*a = malloc(sizeof (int));
return 0;
}
int main() {
int* b = NULL;
malloc2(&b);
}
If an argument only accepts double pointers, how can it accept an address value?
If not to pass the pointer b
by reference through a pointer to it then the function will deal with a copy of the value of the pointer
Changing the copy within the function will not influence on the original pointer.
As a result there the function produce a memory leak.
To change the original pointer b
the function needs a direct access to the pointer. It can be achieved by dereferencing the pointer that points to the pointer (object) b
.
Compare these two demonstrative programs.
#include <stdio.h>
void f( int *p )
{
++p;
printf( "Within the function f p = %p\n", ( void * )p );
}
int main(void)
{
int x = 10;
int *p = &x;
printf( "Before calling f p = %p\n", ( void * )p );
f( p );
printf( "After calling f p = %p\n", ( void * )p );
return 0;
}
The program output is
Before calling f p = 0x7ffc3a940cbc
Within the function f p = 0x7ffc3a940cc0
After calling f p = 0x7ffc3a940cbc
as you can see the pointer p
declared in main was not changed after calling the function f
.
And another program
#include <stdio.h>
void f( int **p )
{
++*p;
printf( "Within the function f p = %p\n", ( void * )p );
}
int main(void)
{
int x = 10;
int *p = &x;
printf( "Before calling f p = %p\n", ( void * )p );
f( &p );
printf( "After calling f p = %p\n", ( void * )p );
return 0;
}
The program output is
Before calling f p = 0x7ffe011131ec
Within the function f p = 0x7ffe011131f0
After calling f p = 0x7ffe011131f0
Now you can see that the pointer p
declared in main was changed after calling the function f
because it was passed to the function by reference through a pointer to it. Dereferencing the pointer to pointer the function gets the direct access to the pointer p
declared in main.
If an argument only accepts double pointers, how can it accept an address value
Each value is interpreted according to its type. The value of this expression &b
has the type int **
. And the function parameter also has the type int **
.
You may imagine the function definition and its call the following way
int main() {
int* b = NULL;
malloc2(&b);
}
//...
int malloc2( /* int **a */ ) {
int **a = &b;
*a = malloc(sizeof (int));
return 0;
}
That is the function parameter a
is initialized by the value of the expression &b
.
Or a more simple example
int main( void )
{
int x = 10;
int *b = &x;
int **a = &b;
}
The function accepts a single int **
argument, i.e. a pointer-to-pointer-to-int.
The variable b
in main
has type int *
, i.e. pointer-to-int. If you then take the address of b
, you now have a pointer-to-pointer-to-int, i.e. int **
which matches the function's argument.