0

I am confused about the pointer when passing to functions in C++, when put *arr in the parameter(line 3), is it means int *arr = balance , I know balance can refer the first element address in the array, but the problem is why arr[i] refers the first element value? I think *arr means value, while arr means address...

#include <iostream>
using namespace std;
double getAverage(int *arr, int size);
int main(){
    int balance[5] = {1000, 2, 3, 17, 50};
    double avg;
    avg = getAverage(balance, 5);
    cout << avg << endl;
    return 0;
}

double getAverage(int *arr, int size){
    int i, sum = 0;
    double avg;
    for (i = 0; i< size; i++){
        sum += arr[i];  //in this line, I think it should sum += *arr[i], arr means a address, isn't?
    }
    avg = double(sum) / size;
    return avg;
}
4daJKong
  • 1,825
  • 9
  • 21

1 Answers1

1

An array identifier cast to a pointer when used with brackets [] or when dereferencing with *, so in main balance is treated as a pointer when not using brackets.

When the brackets are placed after a pointer, they will add an offset to the pointer, based on the size of the object type in memory, then dereference the pointer. Using the * directly on a pointer dereferences the pointer without applying an offset.

So basically *balance and balance[0] will both return the first element in the array.

In C the array is not passed as an object as a function parameter, but rather as a pointer to the first object in the array, which is why the parameter type is int * and you are passing to the function balance, which is a cast to a pointer that points to the first element in the array. Note balance would also behave the same as&(balance[0]) when used in this context.

Jonathon S.
  • 1,928
  • 1
  • 12
  • 18
  • 1
    `balance` is not exactly equivalent to `&(balance[0])`. It depends on the context whether `balance` does decay to a pointer or not: https://godbolt.org/z/6schssh51 – 463035818_is_not_an_ai Sep 03 '21 at 19:01
  • 1
    To help avoid confusion down the line, it's worth emphasizing that arrays themselves are not pointers and will behave very differently from pointers in some contexts. Arrays are effectively pointers only in the sense that C++ will implicitly convert an array to a pointer. This happens in the [exact same way](https://en.cppreference.com/w/cpp/language/implicit_conversion) as, for instance, a `char` being promoted to `int`. – Brian61354270 Sep 03 '21 at 19:02
  • @463035818_is_not_a_number Good point. It would not behave the same in all contexts. Revised to state that this would apply when used as a pointer. – Jonathon S. Sep 03 '21 at 19:07
  • @Brian - Thanks for the feedback. Made the correction. – Jonathon S. Sep 03 '21 at 20:13