I want to allocate an array inside of a function and to be able to use the pointer to that array outside of it as well. I don't know what's wrong with my code
#include <stdio.h>
#include <stdlib.h>
void alloc_array (int **v, int n)
{
*v=(int *)calloc(n,sizeof(int));
printf ("the address of the array is %p",v);
}
void display_pointer (int *v)
{
printf ("\n%p",v);
}
int main()
{
int *v;
alloc_array(&v,3);
display_pointer(v);
return 0;
}
I would expect to get the same address in both printf
s, but that is not the case. What is my mistake?
void alloc_array (int **v, int n)
{
*v = calloc(n,sizeof(int));
printf("the address of the array is %p", *v);
// ----^
}
Note the additional star in my printf
call.
Also, don't cast the return value of malloc
/ calloc
.
v
in alloc_array
contains address of a pointer variable. That variable is v
in main()
.
You don't care about it. Because it won't change. But it the content of v
in main
would.
You should print *v
but why?
Because the content of v
in alloc_array
contains the address of the memory that you allocated.
But display_pointer
doesn't need this. because here you pass the pointer variable itself and the local copy of it in the called function will contain the address of the memory that you allocated.
In this code snippet
int *v;
alloc_array(&v,3);
display_pointer(v);
the function alloc_array
accepts the address of the variable (pointer) v
and this address is outputted in the function
printf ("the address of the array is %p",v);
On the other hand the function display_pointer
accepts the value stored in the variable v
and this value is outputted within the function
printf ("\n%p",v);
Add one more statement in the function alloc_array
and you will see the difference
printf ("the address of the original pointer is %p", ( void * )v);
printf ("the address of the first element of the allocated array is %p", ( void * )*v);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.