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
- Why is it more efficient to sort pointers to structures?ComputerScienceOne · Sorting Pointers to Elements
- How do you pass an array of pointers to structures to a function?ComputerScienceOne · Passing Arrays of Structures
- How do you pass an array of structures to a function to compute an average GPA?ComputerScienceOne · Passing Arrays of Structures
- How should a comparator handle an array of structure pointers with NULL values?ComputerScienceOne · Sorting Pointers to Elements
- How do you access members through a pointer to a structure?ComputerScienceOne · Selection Operators
- How can structures be dynamically allocated?ComputerScienceOne · Declaration & Initialization
- How do you dynamically allocate and initialize a structure?ComputerScienceOne · Selection Operators
- How do you access members of a statically declared structure?ComputerScienceOne · Selection Operators