D@nny said:
hi,
i would like to know how to calculate the size of a dynamic array
created using a dereference declaration like int *numbers and
allocating via malloc or calloc: numbers=(int
*)malloc(sizeof(int)*10);
using sizeof(numbers) will return the pointers size...
is there a possibility?
What you should do is declare a variable, ex. size_t nelements,
that you can use to store the number of elements allocated for
the int array. If you dynamically allocated the array for
10 elements, then store in nelements the value 10. If you
modify the number of array elements, then modify nelements
appropriately. In the occasion where you might need the
total size of the allocation, just multiply the sizeof(int)
with nelements.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *iarr, *tmp;
size_t nelements = 0;
iarr = malloc((sizeof *iarr)*10);
if(iarr) nelements = 10;
printf("Number of elements allocated is %u\n"
"Size of the allocation is %u\n\n",
nelements, nelements*sizeof(int));
if(nelements)
{
puts("An attempt to increase the allocation one element\n");
tmp = realloc(iarr,(sizeof *iarr)*(nelements+1));
if(tmp)
{
iarr = tmp;
nelements++;
}
printf("Number of elements allocated is %u\n"
"Size of the allocation is %u\n\n",
nelements, nelements*sizeof(int));
}
free(iarr);
return 0;
}