Alex Rivera | Logout

Passing an array as a function parameter in C++

Asked 2009-01-14T21:24:11.180
24

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.

Edit
Report

2 Answers

4

if it's nullterminated, strlen() would work.

answered 2009-01-14T21:26:30.987
-3

Dude you can have a global variable to store the size of the array which will be accessible throughout the program. At least you can pass the size of the array from the main() function to the global variable and you will not even have to change the method signature as the size will be available globally.

Please see example:

#include<...>
using namespace std;

int size; //global variable

//your code

void doSomething(char charArray[])
{
    //size available

}
answered 2013-01-16T08:36:22.510

Your Answer