在C中创建结构数组

在C中创建结构数组

我不断收到编译器错误,告诉我它不是如下所示的指针。
c - 在C中创建结构数组-LMLPHP
我不知道我在这里做错了什么。
我在另一个帖子上找到了堆栈溢出的解决方案。

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

最佳答案

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

关于c - 在C中创建结构数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35736937/

10-11 21:04