简体   繁体   中英

Swapping the values of elements in the array using pointers

I recently learnt pointers and began trying simple operations and simple functions with it and I did a swapping function that swaps first value and last value of elements in the array using pointers. Now my question is, while I have two pointers, a pointer basically points to a memory location of another variable correct? So I assigned the two pointers to last and first values of an array and I printed the values and they have swapped. But when I printed the Array the first values and last values, have also swapped. Which is what I do not understand, I only printed the array and didn't include pointers in the printing process.

Here is my code, and would appreciate if someone could explain why the array also swapped its values.

#include <iostream>

#include <ctime>

using namespace std;


void swap(int* swapptr, int arr[], int* swapptr2, int size);

int main() {
int size;
int  arr[] = { 1,2,3,4,5,6 };
int* swap1, * swap2;
size = 6;
swap1 = arr;
swap2 = &arr[size-1];
cout << "The value of the first element is " << *swap1 << " and second element is " << *swap2 << " \n 
\n";

swap(swap1, arr, swap2, size);

cout << "After swap the value of first is " << *swap1 << " and second is " << *swap2 << "\n \n ";
for (int i = 0; i < size; ++i) {
  cout << arr[i] << " ";
}

}




void swap(int* swapptr, int arr[], int*swapptr2, int size) {
int temp = arr[0];
swapptr = arr;
*swapptr2 = arr[size-1];
*swapptr = *swapptr2;
*swapptr2 = temp;


}

Basically, when you are de-referencing the pointer in the swapping function, you are accessing the values stored in the variables the pointers are pointing to

So any change in the pointer's 'values' is reflected in the variables to which they are pointing to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM