Concept

How do you create and use an array of structures in C?

ComputerScienceOne / Arrays of Structures

"Just as we can create arrays of built-in types such as integers, we can also create arrays of our user-defined structures. As an example, the following creates an array of 10 Student structures. Once created, we can treat them like any other array.\n\nStudent *roster = (Student *) malloc(sizeof(Student) * 10);\n\n...\n\ndouble sum = 0.0;\n\nfor(i=0; i<10; i++) {\n\nsum += roster[i].gpa;\n\n}\n\ndouble averageGpa = sum / 10;\n\nAs in the example, we can index each element in the array, roster. Once indexed, each element is a regular structure and so we use the dot operator to access each of its member variables. As with any other array, each element takes up a number of bytes, equal to sizeof(Student). We can swap and reassign each element just like any other variable. For example, the following code swaps the first two elements using a temporary variable.\n\nStudent temp = roster[0];\n\nroster[0] = roster[1];\n\nroster[1] = temp;\n\nEach of these operations copies over every byte that makes up the structure. For small structures, this isn’t that big of a deal. However, for larger structures, this may become an issue, especially if we do this often or pass structures around to functions. As presented, each Student structure takes 40 bytes. This is just an estimate and may vary on different systems and compilers. Usually, compilers use alignment and may pad structures with extra bytes in order to make it more efficient to store in memory. With the first approach, each structure instance is stored contiguously in memory. Swapping two records involves copying entire blocks of 40 bytes."

Related Ideas

How do you create and use an array of structures in C? | ComputerScienceOne | Bifalgorithm | Bifalgorithm