I was required to built a function that allocates memory to a pointer to form an array but whatever I try it doesen't allocate memory .
#include <stdio.h>
#include <stdlib.h>
void alocare(int **a,int n)
{
*a = (int*) malloc(n*sizeof(int));
}
int main()
{
int *a ,*b,*c,n,m,k;
printf("Insert the number of elements for the first array:\n");
scanf("%d",&n);
printf("Insert the number of elements for the second array:\n");
scanf("%d",&m);
printf("Number of bytes ocupied by a before alloc(): %d\n",sizeof(a));
printf("Number of bytes occupied by b before alloc(): %d\n",sizeof(b));
alocare(&a,n);
alocare(&b,m);
printf("Number of bytes ocupied by a after alloc(): %d\n",sizeof(a));
printf("Number of bytes ocupied by b after alloc(): %d\n",sizeof(a));
return 0;
}
The size that it's displayed in the two printf in the main is 4 before allocation and after it and I can't understand why Thanks!
sizeof(a)
returns the size of the type of a
. Since a
is a pointer, its size is always 4
(in your platform; in others it might be 8
or something else). This size will never change: it is a constant for your program.
There is no way to know what is the size of allocated memory behind a pointer unless you save it yourself.