Home > Software design >  How do you properly store structures in C
How do you properly store structures in C

Time:10-08

As the title suggests, I am attempting to store a structure in C but want to find the most efficient way of doing so. The answer certainly depends on the data being stored right?

I know of Linked lists and doubly linked lists, but I'm working with the Periodic Table which comes out to 118 elements with 29 unique fields for each element and I don't know if linked lists are even necessary. Currently, I've tested out storing a few elements and 4 characteristics into a structure array. There are ints, floats, and strings.

element[0] - atomicNumber: 1    element: Hydrogen       symbol: H       atomicMass: 1.0070
element[1] - atomicNumber: 2    element: Helium         symbol: He      atomicMass: 4.0020
element[2] - atomicNumber: 3    element: Lithium        symbol: Li      atomicMass: 6.9410
element[3] - atomicNumber: 4    element: Beryllium      symbol: Be      atomicMass: 9.0120

So, does anyone have any insight that might help guide me?

CodePudding user response:

It depends as much on the data being stored as it does on the way you want to use it. A general pointer: if you know exactly how many elements there will be, a fixed-size array is usually a good idea.

struct Element {
    int atomicNr;
    char symbol;
    // etc
};

Element elements[] = {
    {
       .atomicNr = 1,
       .symbol = 'H', 
    }, 
    // etc
};

You might even be able to get rid of atomicNr and just use the array index for that.

  • Related