c++ - Variable changes value unexpectedly -
i have code supposed store data in in 2 block array.
here code :
#include <iostream> #define position_data 1 #define x_axis 1 #define y_axis 0 using namespace std; typedef int dot_coordinates[position_data]; void set_coordinates(dot_coordinates* dot,int x, int y); int main() { dot_coordinates dot1,dot2,dot3,dot4; set_coordinates(&dot1,0,0); set_coordinates(&dot2,7,0); set_coordinates(&dot3,0,7); set_coordinates(&dot4,7,7); printf("\np1 : x=%d y=%d\n",dot1[x_axis],dot1[y_axis]); printf("\np2 : x=%d y=%d\n",dot2[x_axis],dot2[y_axis]); printf("\np3 : x=%d y=%d\n",dot3[x_axis],dot3[y_axis]); printf("\np4 : x=%d y=%d\n",dot4[x_axis],dot4[y_axis]); return 0; } void set_coordinates(dot_coordinates* dot,int x, int y) { *dot[x_axis] = x; *dot[y_axis] = y; }
the console result following :
p1 : x=0 y=7
p2 : x=7 y=0
p3 : x=0 y=7
p4 : x=7 y=7
shouldn't y=7 y=0 p1 ?
now here happens when replace lines
set_coordinates(&dot1,0,0); set_coordinates(&dot2,7,0); set_coordinates(&dot3,0,7); set_coordinates(&dot4,7,7);
with (the rest of code same)
set_coordinates(&dot2,7,0); set_coordinates(&dot3,0,7); set_coordinates(&dot4,7,7); set_coordinates(&dot1,0,0);
the result here :
p1 : x=0 y=0
p2 : x=0 y=0
p3 : x=0 y=7
p4 : x=7 y=7
i have been trying understand why happening couldn't figure out why p1[x_axis] copying p2[y_axis]. appreciated !
you've defined type 'dot_coordinates' array of length 1 (via position_data macro). then, in set_coordinates function, index second element. undefined behavior, , in particular circumstance, overwriting variables stored in adjacent stack space.
Comments
Post a Comment