Sizeof Operator

Sizeof Operator

When declaring an unbounded array in my function’s parameter list, int a[], can I use the sizeof() operator to determine the array’s length at runtime?

No, you can’t use sizeof for this purpose. The problem is that the compiler silently converts an array parameter to a pointer. Therefore, sizeof will return the size of that pointer, not the size of the array.

You can use a vector object instead of a built-in array. A vector stores the number of its elements in an internal member. You can get the vector’s size by calling the size() member function:

void func( vector  & v){ int sz = v.size();}

If you’re programming in C, you can pass the number of elements in another parameter:

void func( int arr[], int arr_size);


Share the Post: