Santi GS
Santi GS

Reputation: 87

Creating an array of structs in C

I keep getting compiler errors telling me its not a pointer as shown below.

enter image description here

I don't know what I am doing wrong here. I got this solution on stack overflow on another post.

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

Upvotes: 0

Views: 64

Answers (1)

LKW
LKW

Reputation: 180

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

Upvotes: 2

Related Questions