Help with a program with pointers?(reply fast exam tommorow)

This is a part of a practice problem where we have to figure out the output without execution i cant seem to understand. please help.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main () {
int num[4]; int* p;
for (int i=0; i < 4; i++) num[i] = 0;
p = num;
*p = 10;
p++; *p= 20;p++;
*p = 30;
p = &num[3]; *p = 40;
*(p-1) = 30;
for (int n=0; n<4; n++)
cout << num[n] << ", ";
return 0;
} 

i understand why the above code gives output 10,20,30,40

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main () {
int num[4]; int* p;
for (int i=0; i < 4; i++) num[i] = 0;
p = num;
*p = 10;
p++; *(p++) = 20;
*p = 30;
p = &num[3]; *p = 40;
*(p-1) = 30;
for (int n=0; n<4; n++)
cout << num[n] << ", ";
return 0;
}

why does this function the same??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main () {
int num[4]; int* p;
for (int i=0; i < 4; i++) num[i] = 0;
p = num;
*p = 10;
p++; *(++p) = 20;
*p = 30;
p = &num[3]; *p = 40;
*(p-1) = 30;
for (int n=0; n<4; n++)
cout << num[n] << ", ";
return 0;
}

and why this does do sumthing else??

Thank for the help
This is due to the order of operations regarding the prefix and the postfix versions of the incremental operator. The second example says to dereference then increment after assignment which puts us at the second position in the array for the number 20. The third example says to increment then dereference which puts at position three for the assignment of number 20 but that gets overwritten with number 30 in the next operation.
Topic archived. No new replies allowed.