Saptarshi Sahoo
Saptarshi Sahoo

Reputation: 97

Not showing proper values for structure array in c

I was playing with dynamic allocation and pointers and structures so i got a weird result.
Here is the code:-

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define NEW_POINT(x) (POINT *)malloc(x*sizeof(POINT))
#define EXTEND(ptr,size) (POINT *)realloc(ptr,size*sizeof(POINT))

typedef struct p{
  int x;
  int y;
}POINT;
POINT *g;

void show(POINT *s){
  printf("x = %d\ty = %d\n",s->x,s->y );

}
POINT* getPoint() {
  POINT *t = NEW_POINT(1);
  t->x = rand()%50;
  t->y = rand()%50;
  return t;
  //memcpy(g,t,sizeof(*t));
}

int main() {
  POINT *temp;
  srand(time(NULL));
  g = getPoint();
  show(g);
  g  = EXTEND(g,2);
  show(g);
  temp = g;
  temp++;
  temp = getPoint();

  //free(temp);
  show(g);
  show(++g);

return 0 ;
}

I'm here creating two element array, in a bit tricky proccess. I'm expecting that the last to lines should show the g[0] and g[1 ] of the array.
But the output is like this.Output of the program

Please help..

Upvotes: 0

Views: 59

Answers (1)

silversam
silversam

Reputation: 127

The reason why is because your code is not copying the data into the extra space you assigned for a POINT *. I modified the code in main(), to copy the data into that space, the following should work.

int main() {
  POINT *temp;
  srand(time(NULL));
  g = getPoint();
  show(g);
  g  = EXTEND(g,2);
  show(g);
  temp = getPoint();

  /* This line copies the data from the new point referred to by temp
     into the extra space you allocated for g[1].*/
  memcpy(g+1, temp, sizeof(POINT));

  //free(temp);
  show(g);
  show(++g);
  return 0;
}

Upvotes: 1

Related Questions