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);
See also  Comparing different methods of testing your Infrastructure-as-Code

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist