Regarding arrays

Mar 9, 2019 at 4:17pm
Hello,

I have a question regarding arrays. I made the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

void fillInFibonacciNumbers(int result[], int length) {
    result[0] = 0;
    result[1] = 1;
    for (int i = 2; i < length; i++) {
        result[i] = result[i-1] + result[i-2];
    }
}



void printArray(int arr[],int length) {
    
    for (int i = 0; i < length; i++) {
        std::cout << arr[i] << endl;
    }
}


Calling it from main:
1
2
3
4
5
6
 constexpr int length = 10;
    int result[length];
    fillInFibonacciNumbers(result, 10);
    printArray(result, 8);

//gives output 0,1,1,2,3,5 


It works as intended, but how do the main function know that we are taking in the "edited" array when calling printArray, and not the empty array we declared at the top of main?
Mar 9, 2019 at 4:31pm
Arrays are always passed as a "pointer to the first element" of the array.

It's as if you did
fillInFibonacciNumbers(&result[0], 10);

Since there is only one real array in existence (the one in main), any access via a pointer to that array will actually update the array.

It's why you (should) always pass a length when passing an array, since that's the only way to establish it's true length.
Mar 9, 2019 at 4:37pm
Thanks!

then my follow up question is:

is "pass-by-pointer" similar to "pass-by-reference", in the way that both methods can change the passed in object?
Mar 9, 2019 at 4:46pm
Topic archived. No new replies allowed.