struct array in c code example

Example 1: c struct array

#include<stdio.h>
#define n 3

struct Body //Normal struct definition
{
    double radius;
    double mass;
};

struct Body bodies[n]; //Declaration of Struct array

int main()
{
     for(int a = 0; a < n; a++)
     {
            bodies[a].mass = 0; //Access elements of struct array
            bodies[a].radius = 1.0;
     }

    return 0;
}

Example 2: how to create and return a struct array in C

fentry *read_fentries(FILE *fp){
    fentry *files[MAXFILES];

    // EXTRACT FENTRIES AND FNODES FROM FILE
    if ((fread(files, sizeof(fentry), MAXFILES, fp)) == 0) {
        fprintf(stderr, "Error: could not read file entries\n");
        closefs(fp);
        exit(1);
    }
    return files;
}

Tags:

C Example