没有在c中显示结构数组的正确值

时间:2018-04-28 21:41:40

标签: c arrays dynamic struct

我正在玩动态分配和指针和结构,所以我得到了一个奇怪的结果。
这是代码: -

#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 ;
}

我在这里创建了两个元素数组,有点棘手的过程。我期待行的最后一行应该显示数组的g [0]和g [1]。
但输出是这样的。Output of the program

请帮助..

1 个答案:

答案 0 :(得分:1)

原因是您的代码没有将数据复制到为POINT *分配的额外空间中。我修改了main()中的代码,将数据复制到该空间中,以下内容应该可以正常工作。

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;
}
相关问题