I am studying pointers and this is code used as an example that is in the material given by the faculty. I have been replicating this code in my machine and the output is different from the one presented in the material. Code:
#include <stdio.h>
int main()
{
int x=5, y=7, teste=21, aux=17;
int *px, *py;
px = &y;
py = &x;
printf("py - px = %d\n",py-px);
printf("px = %u, *px=%d, &px = %d\n",px, *px, &px);
printf("py = %u, *py=%d, &py = %d\n",py, *py, &py);
px++;
printf("px = %u, px=%d, &px = %d\n",px, *px, &px);
py = px+3;
printf("py = %u, *py=%d, &py = %d\n",py, *py, &py);
printf("py - px = %d\n",py - px);
return 0;
}
The following is the output of the program on my machine:
py - px = -1<br>
px = 3782591132, *px=7, &px = -512376152
py = 3782591128, *py=5, &py = -512376144
px = 3782591136, *px=21, &px = -512376152
py = 3782591148, *py=32767, &py = -512376144
py - px = 3
I also use a IDE Online to study and the exit of the program is the same as this one in college material .
Output in the Online IDE:
py - px = 1
px = 2271354488, *px=7, &px = -2023612824
py = 2271354492, *py=5, &py = -2023612832
px = 2271354492, *px=5, &px = -2023612824
py = 2271354504, *py=593585370, &py = -2023612832
py - px = 3
According to the material, the px pointer points to the variable x and after the increment it should point to the variable y.
However on my machine, it is pointing to the test variable. And in the subtraction line between the px and py pointers the result would be 1 instead of -1.
I do not know what might be wrong.
I'm using Ubuntu 16.4.5 with gcc 5.4 and gcc 7.1 both with the same output. And IDE Online is RED HAT 7.1.1-3 with gcc 7.1.1.