0

Does the size of the parameter arr[] (which is a pointer to an array) matter? I know arr[] is treated as a pointer, does it matter if you put a value in between those brackets? If so why? If not why?

Why is arr[] treated as a pointer? Can it be re-written as int *arr (with no brackets)?

I know the parameter size can take any value, but what about the pointer (int arr[]) pointing to an array?

#include <iostream>
using namespace std;

// function declaration:
double getAverage(int arr[], int size);

int main () {
   // an int array with 5 elements.
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   // pass pointer to the array as an argument.
   avg = getAverage( balance, 5 ) ;

   // output the returned value 
   cout << "Average value is: " << avg << endl; 

   return 0;
}
Euxitheos
  • 325
  • 4
  • 15
  • Arrays get converted to pointers when passed as function parameters. The size of the pointer is irrelevant. – Ron Aug 20 '19 at 12:21
  • The reason why "arr[] treated as a pointer" is because that's how C and C++ works, and this topic, called decaying, should be fully explained in every C++ book. – Sam Varshavchik Aug 20 '19 at 12:30
  • 1
    *does it matter if you put a value in between those brackets?* -- No. It is still a pointer. Do yourself a favor and just use `std::array`, which does not decay, has a `size()` member function, and does intuitively what you expect. – PaulMcKenzie Aug 20 '19 at 12:32
  • When used as a function parameter, `int* p`, `int p[]`, and `int p[N]` are all exactly the same. Why the second two are allowed is something you can only ask the original designers of C. I've never heard a convincing explanation. Sometimes languages designers just make mistakes. – john Aug 20 '19 at 12:33
  • Note that `int arr[]` as an argument is a pointer to `int`, **not** a pointer to an array. In most contexts, the name of an array decays into a pointer to its first element. So `int arr[]` and `int* arr` mean the same thing. – Pete Becker Aug 20 '19 at 12:51

0 Answers0