DDC DDC - 1 month ago 6
C++ Question

Why can you pass an array as a pointer?

I was reading http://www.tutorialspoint.com/cplusplus/cpp_passing_arrays_to_functions.htm and the first method it recommends in passing an array to a function is to pass it as a pointer:

void myFunction(int *myArray) {
.
.
.
}


Wouldn't this not work, because it's impossible to determine the length of
myArray
in
myFunction
?

Answer

The usual convention is to pass a separate parameter for the array length.

void myFunction(int* myArray, int length) {
   for (int index = 0; index < length; ++index) {
      // ... do something with each array item ...
   }
}

void caller() {
    int array[10];
    // ... put some useful values in the array ...
    myFunction(array, sizeof(array) / sizeof(array[0]));
}