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.

5/24/2009 6:22:48 AM

Accepted Answer

Without changing the signature? Append a sentinel element. For char arrays specifically, it could be the null-terminating '\0' which is used for standard C strings.

void doSomething(char charArray[])
    char* p = charArray;
    for (; *p != '\0'; ++p)
         // if '\0' happens to be valid data for your app, 
         // then you can (maybe) use some other value as
         // sentinel
    int arraySize = p - charArray;

    // now we know the array size, so we can do some thing

Of course, then your array itself cannot contain the sentinel element as content. For other kinds of (i.e., non-char) arrays, it could be any value which is not legal data. If no such value exists, then this method does not work.

Moreover, this requires co-operation on the caller side. You really have to make sure that the caller reserves an array of arraySize + 1 elements, and always sets the sentinel element.

However, if you really cannot change the signature, your options are rather limited.

1/14/2009 9:48:12 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow