Member-only story
In C++, how to manipulate the elements in an array with pointers
Question
Update the array values from { 5, 10, 15 } to { 30, 20, 10 } using pointers. In the end of the method, print out the elements in the array using pointers as well.
Solution
int main(){int arr[3] = { 5, 10, 15 };int* ptr = arr;*ptr = 10; // set arr[0] to 10*(ptr + 1) = 20; // set arr[1] to 20ptr += 2;ptr[0] = 30; // set arr[2] to 30ptr++;while (ptr > arr){ptr--;cout << ' ' << *ptr; // print values}cout << endl;}
Explanation (line by line)
int* ptr = arr;
The above line declares the variable ‘ptr’ to the array. The current memory address that this pointer will have the first element of this array. The ‘*’ is important as it declares the variable as a pointer.
*ptr = 10;
The above line shows that the value 10 is overriding the current value in the pointer.
ptr += 2;ptr[0] = 30; // set arr[2] to 30
ptr += 2 is the asme as ptr = ptr+2
This line shifts the pointer by 2 indices to the right. So now the pointer is at index 3. Therefore, ptr[0]=30 will override the 3rd element in the array to the value of 30.