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.
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.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 + 1elements, and always sets the sentinel element.However, if you really cannot change the signature, your options are rather limited.