C++ – Passing an array as a function parameter in C++


In C++, arrays cannot be passed simply as parameters. Meaning if I create a function like so:

void doSomething(char charArray[])
    // if I want the array size
    int size = sizeof(charArray);
    // NO GOOD, will always get 4 (as in 4 bytes in the pointer)

I have no way of knowing how big the array is, since I have only a pointer to the array.

Which way do I have, without changing the method signature, to get the size of the array and iterate over it's data?

EDIT: just an addition regarding the solution. If the char array, specifically, was initialized like so:

char charArray[] = "i am a string";

then the \0 is already appended to the end of the array. In this case the answer (marked as accepted) works out of the box, so to speak.

Best Solution

Use templates. This technically doesn't fit your criteria, because it changes the signature, but calling code does not need to be modified.

void doSomething(char charArray[], size_t size)
   // do stuff here

template<size_t N>
inline void doSomething(char (&charArray)[N])
    doSomething(charArray, N);

This technique is used by Microsoft's Secure CRT functions and by STLSoft's array_proxy class template.