2
I’m studying pointers and this is a code used as an example that’s in the material given by the college. I went to replicate this code on my machine and the output is different from 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;
}
Just below 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 C to study and exit from the program is the same as this 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 pointer px points to the variable x and after the increment it should point to the variable y.
Yet on my machine, it’s pointing to the variable test. And on the line of subtraction between pointers px and py the result would be 1 and not -1.
I don’t know what could be wrong.
I am using Ubuntu 16.4.5 with gcc 5.4 and gcc 7.1 both with same output. And the Online IDE is RED HAT 7.1.1-3 with gcc 7.1.1.
You have no guarantee that
x
andy
are consecutive. The compiler is free to put the desired order– Jefferson Quesado