簡體   English   中英

在C中創建結構數組

[英]Creating an array of structs in C

我不斷收到編譯器錯誤,告訴我它不是一個指針,如下所示。

在此處輸入圖片說明

我不知道我在做什么錯。 我在另一篇文章的堆棧溢出中得到了這個解決方案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM