0

I'm new in programming, so please forgive in case of any mistakes.

I created an array using dyanamic allocation, and put the values in it. While finding the length of the array,I'm getting 2 as answer.

what's the reason ?

int *arr;
    arr=(int*)calloc(5,sizeof(int));
   
    arr[0]=1,arr[1]=2,arr[2]=3,arr[3]=4,arr[4]=5;
    printf("%ld",sizeof(arr)/sizeof(arr[0]));

Since the array size is allocated to be 5 the length should be 5 , but in compiler it's showing 2.

  • You can't find the size like that. It only works for actual arrays in the scope that they are declared. You need to keep track of what you allocated and pass that along with the pointer to any function that needs that information. – Retired Ninja May 27 '23 at 20:02
  • `arr` is a pointer. The array is what it points to.. – stark May 27 '23 at 20:07
  • If you want to make the size of the array a part of the type you could make it`int (*arr)[5];` and then use it like so: `(*arr)[0] = 1;` etc. You'd then get the number of elements in the array with `sizeof *arr / sizeof **arr`. – Ted Lyngmo May 27 '23 at 20:20
  • `sizeof arr` gives you the size of the pointer, not the size of the memory to which it points; there's no way to query the size of the allocated memory. You'll have to keep track of that yourself. – John Bode May 27 '23 at 20:29

0 Answers0