-1

I am practicing Pointer Arithmetic but printf statement has a confusing response. My understandin says first 101 should be printed and then increment should occur. But here the problem goes...

#include <stdio.h>

int main()
{
int a[] = {101, 276, 345};
int *ptr = a;
printf ("%d\n%d\n", *ptr, *(++ptr) );
return 0;
}

It produces the following output

276
276

But, when I change the code to following

#include <stdio.h>

int main()
{
int a[] = {101, 276, 345};
int *ptr = a;
printf ("%d\n", *ptr);
return 0;
}

Result is following

101
Saad
  • 87
  • 6
  • My knowledge says the answer should be 101 276 – Saad Aug 22 '20 at 05:11
  • 2
    Welcome to *Undefined Behavior* - in `printf ("%d\n%d\n", *ptr, *(++ptr) );` the value of `ptr` is indeterminate as there is no defined order the parameters are evaluated in -- the order of evaluation is indeterminate. Is `++ptr` applied first or not? `printf ("%d\n%d\n", *a, *(++ptr) );` would be fine. – David C. Rankin Aug 22 '20 at 05:11
  • 1
    This has little to do with pointer arithmetic. You would have the same problem if you were printing integers like that. – Barmar Aug 22 '20 at 05:12
  • Stop practicing 'clever' code where its behavior is difficult to understand at a glance. Break it up into smaller steps, often using more temporary variables. – Martin James Aug 22 '20 at 07:10

1 Answers1

0

++ptr changes the original pointer, try ptr + 1 instead of ++ptr

#include <stdio.h>

int main()
{
int a[] = {101, 276, 345};
int *ptr = a;
printf ("%d\n%d\n", *ptr, *(ptr + 1) );
return 0;
}