Hello.,
Im very new to C++ but im trying to resolve a fragment of the following code:
#include <iostream>
using namespace std;
const int NO_STEPS = 4;
void s(int* a, int i);
int main ( ) {
int i, a[NO_STEPS] = {2, 4, 1, 3};
for ( i = 0; i < NO_STEPS; i++ )
s( a, i );
for ( i = NO_STEPS - 1; i >= 0; i-- )
cout << a[i] << ' ';
cout << "Boom!\n";
return 0;
}
void s(int* a, int i) {
int* p;
int x, n = NO_STEPS / 2;
if (i != n) {
p = a + i; // be careful - pointer addition here
x = *p;
*p = a[n];
a[n] = x;
}
}
to understand it better i split the code into 2 parts and simplified it abit so im working only on the first loop having the following code:
#include<iostream>
using namespace std;
void s(int* a, int i);
main()
{
int i, a[4] = {2,4,1,3};
for(i = 0; i < 4; i++)
{
s(a,i);
printf("%d", a[i]);
}}
void s(int *a, int i)
{
int *p; int x, n=2;
if(i != 2)
{
p = a + i;
x = *p;
*p = a[2];
a[2] = x;
}}
going through it on paper i dont fully understand the last line of function a[2] = x; we already know what the x is and we already stored it in a[2], why to restore the same value to x??? and my result was very different on paper then compilers, here are the arrays values i got after the loop is complete 2114, when the compiler got 1244, could anybody please let me know where my problem is? its driving me nuts.
Thank you very much