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.
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.
Example01:
Output:
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
21 tonumbers
, you are actually adding1 * sizeof (int)
tonumbers
.On a typical system, this means the following are true, because
int
integers typically use 4 bytes.Example02:
Output: