1

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?

DDC
  • 115
  • 4
  • 1
    It depends what you mean by "work". – juanchopanza Nov 03 '16 at 23:13
  • `myFunction` needs the length of the array to work. For example, one of the operations `myFunction` performs is to add up all the elements of `myArray`. – DDC Nov 03 '16 at 23:15
  • I can guarantee that a C++ compiler will not have any problem passing an array of `int`s to this function. This will most certainly work. – Sam Varshavchik Nov 03 '16 at 23:15
  • @DDC so, it doesn't "work". That should be plain to see, no? – juanchopanza Nov 03 '16 at 23:15
  • 1
    In the end you actually pass a pointer to the first element of the array. How you treat the pointer after that is up to you. – Captain Obvlious Nov 03 '16 at 23:17
  • @juanchopanza Okay, so for what application might passing an array like this actually be useful? Perhaps when the size of the array is agreed upon a priori? – DDC Nov 03 '16 at 23:18
  • 2
    @DDC It is hardly ever useful. If you have a sentinel value indicating the end of the range, that can work. This is what happens with null terminated strings being passed as `char*`. In C++ you pass either objects that know their size (e.g. `std::vector`) or pairs of iterators defining a range. – juanchopanza Nov 03 '16 at 23:19

1 Answers1

3

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]));
}
dan04
  • 87,747
  • 23
  • 163
  • 198