-7

in this code, if I write " *p++=*q " instead of " *p++ " nothing changes. Why?

int a[10]={1,2,3,4,5,6,7,8,9,10};
int *p=a, *q=&a[8];

*p++;

printf("%d  \n", *p);
printf("%d  \n", *q);
printf("%d  \n", p);
printf("%d  \n", q);

2 Answers2

3

*p++; means

  1. increment p and get its value before incrementing
  2. dereference the value
  3. throw the result away

*p++=*q; means

  1. increment p and get its value before incrementing
  2. dereference the value to know where to store
  3. dereference q
  4. store the data read

(the actual order of evaluation is unspecified and may differ)

Changing it do changes. You didn't observe the change because you didn't check the value stored in p[-1] (p is value after incrementing).

Note that the lines

printf("%d  \n", p);
printf("%d  \n", q);

invoke undefined behavior by passing data having wrong value to printf. The lines should be

printf("%p  \n", (void*)p);
printf("%p  \n", (void*)q);

Use %p specifier and cast the pointer to print to void* to print pointers via printf.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

Your question is wrong. You claim "nothing changes" and ask why.

The reality is that something changed. But not any of the things you were looking at. Go and figure out what changed.

On top of that, printing p and q with a %d modifier is undefined behaviour.

I have £5 in my wallet. I put £10 in my sock. I check my wallet, and there is still £5 in my wallet. Nothing changed. Why?

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • 1
    Unless you say what *did* change, this is better as a comment (and in fact you did post it as a comment, so why post the non-answer too?). – interjay Jun 05 '16 at 15:00
  • A logically valid question can be still be based on an incorrect assumption, IMHO, @alk – user3078414 Jun 05 '16 at 15:10