Pointers’ Arithmetic
Why did we go deep into arrays while learning pointers? The fact is that the array’s name is a pointer to its first element.
We can get the address of the first element of the array by its name or by declaring the pointer:
12345int arr[5]{1, 2, 3, 4, 5}; int *p = &arr[0]; cout << p << endl; cout << arr << endl;
In other words, indexing is equivalent to adding (or substructing) to the pointer:
12cout << *(p+2) << endl; // equivalent to arr[2] cout << *(arr+2) << endl; // equivalent to arr[2]
The for loop we used to go through the arrays can also be used with pointers by adding 1 on each step, but we will use these feature pointers in work with functions and dynamic memory in the following sections.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Still meg spørsmål om dette emnet
Oppsummer dette kapittelet
Vis eksempler fra virkeligheten
Awesome!
Completion rate improved to 2.94
Pointers’ Arithmetic
Sveip for å vise menyen
Why did we go deep into arrays while learning pointers? The fact is that the array’s name is a pointer to its first element.
We can get the address of the first element of the array by its name or by declaring the pointer:
12345int arr[5]{1, 2, 3, 4, 5}; int *p = &arr[0]; cout << p << endl; cout << arr << endl;
In other words, indexing is equivalent to adding (or substructing) to the pointer:
12cout << *(p+2) << endl; // equivalent to arr[2] cout << *(arr+2) << endl; // equivalent to arr[2]
The for loop we used to go through the arrays can also be used with pointers by adding 1 on each step, but we will use these feature pointers in work with functions and dynamic memory in the following sections.
Takk for tilbakemeldingene dine!