Passing Arrays into Functions

Why can I calculate the number of elements in array foo with sizeof(foo)/sizeof(foo[0]), but if I use the same calculation inside the functions squares_calculator I keep getting 1 as the length?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Question 11:
int squares_calculator(const int arr[]){
    int norm = 0;
    int length_of_array = sizeof(arr)/sizeof(arr[0]);
    cout << "Lenth of array is " << length_of_array << endl;
    for(int i = 0; i < length_of_array; ++i){
        int square = arr[i] * arr[i];
        cout << "Square: " << square << endl;
        norm += square;
    }
    return norm;
}


int main()
{
    int foo[5] = {-3,5,6,-5,10};
    cout << squares_calculator(foo) << endl;

    cout << "Lenght of Foo is:" << sizeof(foo)/sizeof(foo[0]);
}
When you pass an array into a function, it degrades into just a pointer and now sizeof(arr) just is the size of a pointer instead of the whole array.

In general when you pass raw arrays into functions, you will also want to also pass the size of array.

Also consider std::array which can contain size information conveniently for you.
http://en.cppreference.com/w/cpp/container/array
Last edited on
Thanks for the quick explanation.
I just want to ask if my understanding is correct based on the code below. This is a solution posted to a homework problem by my prof.

So the function below takes in two pointers, one points to the start of the array, the other points to one past the last element of the array. "double result" will be used to add the absolute values of each element in the array.

To access the elements in the array we start with "start" to access the first element, then to access the next one, we use "start++" which means we now look at the next element in the array and keep incrementing "start" until we get to just one before the "end" pointer. At this point the bool statement in the while loop is now false, then "result" is returned.

1
2
3
4
5
6
7
8
9
10
11
12
13
double sum_of_elements_of_an_array(double* start, double* end) {
    double result = 0.0;
    while (start < end) {
        result += abs(*start);
        start++;
    }
    return result;
}

int main(){
    double foo [3] = {1.3,2.4,3.5};
    sum_of_elements_of_an_array(foo, foo + 3);
}
Last edited on
closed account (48T7M4Gy)
It also depends whether the array you are passing has a termination element. For instance if you terminate an array of positive integers with -1, then the size of the array is not required, just test for -1. Or count up to terminator if you need the array's size once it's been passed.
Topic archived. No new replies allowed.