0
Can anyone explain this code too?
#include <stdio.h> int main() { char* ptr = "MadeEasy"; char a,b; for(int i=0;i<3;i++){ a = *++ptr; b = *ptr++; } printf("%c %c", a,b); return 0; }
1 Odpowiedź
+ 1
The output is "a a". The "a" comes from the second "a" in "MadeEasy".
ptr is a pointer that starts being the address of the M in "MadeEasy".
Iteration where i = 0:
a is set to the first "a" in MadeEasy by running "a = *++ptr" because ++ptr adds 1 to ptr and * gets the value at that address. In other words, it gets the character after M in MadeEasy.
b is set to the first "a" in MadeEasy also. This is because the *ptr is evaluated before adding 1 to ptr.
Iteration where i = 1:
a and b are set to the "e" from MadeEasy and ptr is left pointing at the "E".
Iteration where i = 2:
a and b are set to the second "a" from MadeEasy and ptr is left pointing at the "s".
When i = 3, the for-loop ends because 3 < 3 is false.
The printf prints "a a" because both a and b variables hold the value of "a".