-1

Test platform is Linux 32 bit.

I found a bug in my code, and I don't know why....

I simplified this code and put it here:

unsigned int aa  = 0;
unsigned int array[10000];
unsigned int* ptr = array + 2000;

printf("aa: %d ", aa);   // value 1
printf("ptr: %d \n", ptr);  //value 2
printf("aa+ptr: %d \n", aa + ptr);  // value 3

compiler is gcc version 4.6.3

It seems silly but I don't understand why value3 != value1 + value2

Could anyone give me some help?

Thank you!

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
lllllllllllll
  • 8,519
  • 9
  • 45
  • 80
  • In cygwin (32-bit), with `gcc version 4.8.2 (GCC)` , I get the expected output: `aa: 0 ptr: 2633512 aa+ptr: 2633512`. Are you posting your actual code? – Jonathon Reinhart Jan 28 '14 at 22:37
  • Also, while you're playing with pointers, it may help to make sure you understand how [pointer arithmetic](http://stackoverflow.com/questions/394767/pointer-arithmetic) works. Basically, adding one to a pointer advances it to the next "element", increasing the value of the pointer by `sizeof(*p)` bytes. – Jonathon Reinhart Jan 28 '14 at 22:42
  • What values are you expecting, and what values are you actually seeing? – John Bode Jan 28 '14 at 22:49

1 Answers1

6

In the second and third cases, you're passing a pointer to printf, but using %d as a formatter. You need %p.

ints and pointers are not interchangeable.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • But on Linux 32-bit, `sizeof(int)==sizeof(void*)`. Printing pointers with `%d` is largely useless, but this should still work just fine. – Jonathon Reinhart Jan 28 '14 at 22:32