I have dynamically allocated a structure array representing a series of points. However, when I try to assign values to its members, the program assigns different values than it is supposed to. What am I doing wrong?
Output of the program:
xy[0].x= 0
xy[0].y= 0
xy[1].x= 1
xy[1].y= 1
xy[2].x= 2
xy[2].y= 2
xy[3].x= 1041
xy[3].y= 0
Code:
#include <stdio.h>
#include <stdlib.h>
int n;
struct point{
int x,y;
};
typedef struct point Point;
void resize(Point*xy)
{
xy=(Point*)realloc(xy,sizeof(Point));
for (n=0;n<4;n++)
{
xy[n].x=n;
xy[n].y=n;
}
}
int main ()
{
Point *xy;
xy=(Point*)malloc(2*sizeof(Point));
for (n=0;n<2;n++){
xy[n].x=n;
xy[n].y=n;
}
resize(xy) ;
for (n = 0; n<4; n++) {
printf("xy[%i].x= %i \n",n,xy[n].x);
printf("xy[%i].y= %i \n",n,xy[n].y);
}
free(xy);
return 0;
}