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.


For C, you have to pass the length (number of elements)of the array.

For C++, you can pass the length, BUT, if you have access to C++0x, BETTER is to use std::array. See here and here. It carries the length, and provides check for out-of-bound if you access elements using the at() member function.


Why don't you use function templates for this (C++)?

template<class T, int N> void f(T (&r)[N]){
}

int main(){
    int buf[10];
    f(buf);
}

EDIT 2:

The qn now appears to have C tag and the C++ tag is removed.

Tags:

C

Arrays