Study and comment the struct allocation, access, and deallocation examples below:
#include <cstdio> #include <cstdlib> struct infoStruct { int intField; string strField; float* fptrField; }; const int Size1 = 3; const int Size2 = 2; int main() { int i, j; infoStruct arr[Size1]; printf("Initializing array of infoStructs\n"); for (i = 0; i < Size1; i++) { arr[i].intField = i; arr[i].strField = "test1"; arr[i].fptrField = new float[Size2]; for (j = 0; j < Size2; j++) arr[i].fptrField[j] = 1 + j * 0.25; } infoStruct *infPtr; printf("Displaying array of infoStructs\n"); infPtr = arr; for (i = 0; i < Size1; i++) { printf("%d,", arr[i].intField); printf("%s,", arr[i].strField); for (j = 0; j < Size2; j++) { printf("%g,", arr[i].fptrField[j]); } printf("\n"); } printf("\n"); printf("Dynamically allocating array of infoStructs\n"); infPtr = new infoStruct[Size1]; printf("Initializing dynamic array of infoStructs\n"); for (i = 0; i < Size1; i++) { arr[i].intField = 0; arr[i].strField = "test2"; arr[i].fptrField = new float[Size2]; for (j = 0; j < Size2; j++) arr[i].fptrField[j] = 1 + j * 0.25; } printf("Deallocating old dynamic array\n"); delete [] infPtr; printf("Allocating new single infoStruct\n"); infPtr = new infoStruct; infPtr->intField = 1; infPtr->strField = "test3"; infPtr->fptrField = new float[Size2]; for (j = 0; j < Size2; j++) infPtr->fptrField[j] = 0.1 + j; printf("Displaying infoStruct using ptr->field notation\n"); printf("%d,", infPtr->intField); printf("%s,", infPtr->strField); for (j = 0; j < Size2; j++) { printf("%g,", infPtr->fptrField[j]); } printf("\n\n"); printf("Displaying infoStruct using (*ptr).field notation\n"); printf("%d,", (*infPtr).intField); printf("%s,", (*infPtr).strField); for (j = 0; j < Size2; j++) { printf("%g,", (*infPtr).fptrField[j]); } printf("\n\n"); printf("Deallocating the single infoStruct\n"); delete infPtr; printf("\n"); return 0; } |
Resulting output:
Initializing array of infoStructs Displaying array of infoStructs 0,test1,1,1.25, 1,test1,1,1.25, 2,test1,1,1.25, Dynamically allocating array of infoStructs Initializing dynamic array of infoStructs Deallocating old dynamic array Allocating new single infoStruct Displaying infoStruct using ptr->field notation 1,test3,0.1,1.1, Displaying infoStruct using (*ptr).field notation 1,test3,0.1,1.1, Deallocating the single infoStruct |