Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

C++: The Relationship between Arrays and Pointers #207

Open Qingquan-Li opened 2 years ago

Qingquan-Li commented 2 years ago

Concept: Array names can be used as constant pointers, and pointers can be used as array names.

An arry name, wihout brackets and a subscript, actually represents the starting address of the array. This means that an array name is really a pointer.

array[index] is equivalent to *(array + index)

Example01:

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    cout << numbers << endl;
    cout << *numbers << endl;       // 10
    cout << *(numbers + 1) << endl; // 20

    for (int i = 0; i < sizeof(numbers) / 4; i++)
        cout << numbers[i] << " ";

    cout << endl;
    // array[index] is equivalent to *(array + index)
    for (int i = 0; i < sizeof(numbers) / 4; i++)
        cout << *(numbers + i) << " ";
    return 0;
}

Output:

0x16d827670
10
20
10 20 30 40 50 
10 20 30 40 50 

Because (array) numbers works like a pointer to the starting address of the array, the first element is retrieved when (array) numbers is dereferenced.

In C++, when you add a value to a pointer, you are acturally adding that value times the size of the data type being referenced by the pointer.

In other words, if you add 2 1 to numbers, you are actually adding 1 * sizeof (int) to numbers.

On a typical system, this means the following are true, because int integers typically use 4 bytes.

*(numbers + 1) // is actually *(numbers + 1 * 4)
*(numbers + 2) // is actually *(numbers + 2 * 4)
*(numbers + 3) // is actually *(numbers + 3 * 4)


Example02:

#include <iostream>

using namespace std;

int main() {
    const int SIZE = 5;
    double arr[SIZE] = {1.5, 3.14, 3.5, 4.5, 5.5};
    double* ptr = arr;

    // The output is the same:
    cout << "Printing arr: " << arr << endl;
    cout << "Printing address of arr[0]: &arr[0]: " << &arr[0] << endl;
    cout << "Printing address of arr[0]: &arr+0: " << &arr+0 << endl;

    for (int i = 0; i < SIZE; i++) {
        // cout << (arr + i) << " ";
        cout << (ptr + i) << " ";
    }
    cout << endl;

    for (int i = 0; i < SIZE; i++) {
        // cout << *(arr + i) << " ";
        cout << *(ptr + i) << " ";
    }
    cout << endl;

    // The output is the same as the for loop above:
    for (int i = 0; i < SIZE; i++) {
        cout << *ptr << " ";
        ptr++; // Plus one double to the memory address (because arr's data type is double.
    }

    return 0;
}

Output:

Printing arr: 0x16bb97660
Printing address of arr[0]: &arr[0]: 0x16bb97660
Printing address of arr[0]: &arr+0: 0x16bb97660
0x16bb97660 0x16bb97668 0x16bb97670 0x16bb97678 0x16bb97680 
1.5 3.14 3.5 4.5 5.5 
1.5 3.14 3.5 4.5 5.5