OiciTrap OiciTrap - 1 year ago 58
C Question

Trying to understand this sentence with a pointer

I'm trying to understand why do i have this output.

a[0]: 5, a[1]: 5, ptr: 5

From this little program.

#include <stdio.h>

int main() {
int a[2] = {5, 10};
int *ptr = a;

*ptr = *(ptr++);

printf("a[0]: %d, a[1]: %d, ptr: %d\n", a[0], a[1], *ptr);

return 0;

The part that I don't understand is.

*ptr = *(ptr++);

Because according to me what should happen is that ptr should point to 10, and nothing more, because ++ postfix should increment ptr after the allocation, so according to me this should allocate the value of a[0] to a[0] (which would not affect anything) and after this ptr should be pointing to the 10 on a[1], but what really happens is that at the end a[1] is also 5, can someone explain this to me?.

Answer Source

What you are seeing is undefined behavior. The language does not guarantee whether the LHS is evaluated first or the RHS is evaluated first. A platform can choose which side gets evaluated first.

Looks like in your platform, the RHS is evaluated first.

The value of RHS, is 5. The side effect is ptr to point to a[1].

Then, it is assigned to *ptr, which is a[1].

Caution This style of programming is strongly discouraged in the real world since the compiler can do anything it chooses to. See http://en.wikipedia.org/wiki/Undefined_behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download