-2

if i have a function which passes an array as a argument. Is there any way to calculate the array size in called function, if size is also not passed as an argument . here is snippet:

void array_size(int array[])
{
  //How i can calculate the array size here
}

int main()
{
   int a[]={1,2,3};
   array_size(a);
}
Vineet
  • 307
  • 1
  • 3
  • 12

1 Answers1

1

Inside the array_size() function, the "array" is a pointer. It gets converted to a pointer to its first element in the calling function.

If you need to know the size, you need to pass it around. In the main() function, a is an array and you can calculate the number of elements with

number_of_elements = sizeof a / sizeof *a;

then pass that to the function (which needs updating)

array_size(a, number_of_elements);
//         ^ the array is converted to a pointer to its first element
pmg
  • 106,608
  • 13
  • 126
  • 198