0

Why does this code print 5 4 3 2 1 instead of 1 2 3 4 5?

#include <iostream> using namespace std; int main(){ int x[5] = {1,2,3,4,5}; int* p = x; int i; for (i = 0; i < 2; i++){ int temp = *(p + i); *(p + i) = *(p + 4 -i); *(p + 4 - i) = temp; } for (i = 0 ; i < 5; i++) cout << x[i] << " "; return 0; }

26th Dec 2020, 1:33 PM
Glade
Glade - avatar
2 Réponses
+ 4
For i=0 , temp = 1; *(p+i)=5; *(p+4-i)=temp; suppose p has a address of 102064 it is now being increased by 0 bytes as 0*2 =0 so new memory address is 102064 which is pointing to number 1 in array x ,so what *(p+i)=*(p+4-i) is telling to compiler is to store the value located at (p+4-i)(equates to 5 after dereferencing(* is used for dereferencing)) address to to the address *(p+i) which is 102064 and so this is how 1 and 5 are being swapped , Hopefully it's clear enough or otherwise let me know
26th Dec 2020, 2:05 PM
Abhay
Abhay - avatar
+ 3
You are swapping the array, so you are getting 5, 4, 3, 2, 1 instead of 1, 2, 3, 4, 5. You have taken array of 1, 2, 3, 4, 5 but in first for loop you are swapping first two elements with last two elements. So, it is printing in reverse.
26th Dec 2020, 2:01 PM
Padala Vamsi
Padala Vamsi - avatar