我不断收到编译错误,告诉我它不是指针,如下所示。
我不知道我在这里做错了什么。 我在另一篇文章中得到了关于堆栈溢出的解决方案。
typedef struct Data{
int x;
int y;
}Data;
int main (void){
Data * arrData = malloc (sizeof * arrData *6);
for (int i =0; i<6;i++){
arrData[i] = NULL;
}
for (int i =0; i < 6; i++){
printf("This is an iteration.\n");
arrData[i] = malloc (sizeof * arrData[i]);
int tempx;
int tempy;
printf("Add x and y\n");
scanf ("%d %d",&tempx,&tempy);
arrData[i] -> x = tempx;
arrData[i] -> y = tempy;
}
for (int i =0; i<6; i++){
printf("x: %d y: %d\n",arrData[i]->x,arrData[i]->y);
}
free (arrData);
return 0;
}
答案 0 :(得分:2)
typedef struct Data{
int x;
int y;
}Data;
int main(void){
//By doing this, you are allocating a 6 Data large memory space
Data * arrData = (Data*)malloc(sizeof(Data)* 6);
//you don't need this
//for (int i = 0; i<6; i++){
// arrData[i] = NULL;
//}
for (int i = 0; i < 6; i++){
printf("This is an iteration.\n");
//you don't need this
//arrData[i] = malloc(sizeof * arrData[i]);
int tempx;
int tempy;
printf("Add x and y\n");
scanf("%d %d", &tempx, &tempy);
//If pointer to struct, use ->, otherwise, use .
arrData[i].x = tempx;
arrData[i].y = tempy;
}
for (int i = 0; i<6; i++){
printf("x: %d y: %d\n", arrData[i].x, arrData[i].y);
}
free(arrData);
return 0;
}