Concept
How can an array of structure pointers make swapping structures more efficient?
ComputerScienceOne / Arrays of Structures
"As an alternative, we could instead deal indirectly with structures by creating an array of pointers to structures. Swapping elements then involves only copying pointer values rather than every byte that makes up the structure. To do this, we use the familiar pointer-to-pointer syntax.\n\nStudent **roster = (Student **) malloc(sizeof(Student *) * 10);\n\nfor(i=0; i<10; i++) {\n\nroster[i] = (Student *) malloc(sizeof(Student) * 1);\n\n}\n\n//access each as pointers and use the arrow operator\n\nroster[0]->id = 87654321;\n\nroster[0]->gpa = 4.0;\n\n//swap the first two *pointers*:\n\nStudent *temp = roster[0];\n\nroster[0] = roster[1];\n\nroster[1] = temp;\n\nAs in the example above, if each element in the array is a pointer to a structure, then we use the arrow operator to access each member variable. The differences between these two approaches is illustrated in Figures 23.1 and 23.2. In contrast, using pointers to structures means that structures may be stored non-contiguously in different memory locations. Swapping two structures is done indirectly by swapping pointers, only 8 bytes. The difference in this particular example is not that great, 8 vs. 40 bytes, but with larger structures it can become an issue. Each approach has its own advantages and disadvantages and one may be more appropriate than the other in different situations. Figure 23.2 illustrates an array of structure pointers in which each record is a pointer that refers to a structure that may be stored non-contiguously in completely different memory locations."
Related Ideas
- How do you pass an array of pointers to structures to a function?ComputerScienceOne · Passing Arrays of Structures
- Why is it more efficient to sort pointers to structures?ComputerScienceOne · Sorting Pointers to Elements
- What is 355 24?ComputerScienceOne · Passing Arrays of Structures . . . . . . . . . . . . . . . . . . . . .
- What dynamic data structures does the C standard library provide?ComputerScienceOne · Dynamic Data Structures
- How do you pass an array of structures to a function to compute an average GPA?ComputerScienceOne · Passing Arrays of Structures