How do you get the size of array that is passed into the function?

You need to also pass the size of the array to the function.
When you pass in the array to your function, you are really passing in the address of the first element in that array. So the pointer is only pointing to the first element once inside your function.

Since memory in the array is continuous though, you can still use pointer arithmetic such as (b+1) to point to the second element or equivalently b[1]

void print_array(int* b, int num_elements)
{
  for (int i = 0; i < num_elements; i++)
    {
      printf("%d", b[i]);
    }
}

This trick only works with arrays not pointers:

sizeof(b) / sizeof(b[0])

… and arrays are not the same as pointers.

Leave a Comment