How do you make an array of structs in C? How do you make an array of structs in C? c c

How do you make an array of structs in C?


#include<stdio.h>#define n 3struct body{    double p[3];//position    double v[3];//velocity    double a[3];//acceleration    double radius;    double mass;};struct body bodies[n];int main(){    int a, b;     for(a = 0; a < n; a++)     {            for(b = 0; b < 3; b++)            {                bodies[a].p[b] = 0;                bodies[a].v[b] = 0;                bodies[a].a[b] = 0;            }            bodies[a].mass = 0;            bodies[a].radius = 1.0;     }    return 0;}

this works fine. your question was not very clear by the way, so match the layout of your source code with the above.


So to put it all together by using malloc():

int main(int argc, char** argv) {    typedef struct{        char* firstName;        char* lastName;        int day;        int month;        int year;    }STUDENT;    int numStudents=3;    int x;    STUDENT* students = malloc(numStudents * sizeof *students);    for (x = 0; x < numStudents; x++){        students[x].firstName=(char*)malloc(sizeof(char*));        scanf("%s",students[x].firstName);        students[x].lastName=(char*)malloc(sizeof(char*));        scanf("%s",students[x].lastName);        scanf("%d",&students[x].day);        scanf("%d",&students[x].month);        scanf("%d",&students[x].year);    }    for (x = 0; x < numStudents; x++)        printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);    return (EXIT_SUCCESS);}


Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct{    double p[3];//position    double v[3];//velocity    double a[3];//acceleration    double radius;    double mass;}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},                   {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},                   {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.