I have to use the following block of code for a school assignment, STRICTLY WITHOUT ANY MODIFICATIONS.
typedef struct
{
char* firstName;
char* lastName;
int id;
float mark;
}* pStudentRecord;
pStudentRecord* g_ppRecords;
int g_numRecords =0;
Here g_ppRecords is supposed to be an array of pointers to structs. What I am completely failing to understand is that how can the statement pStudentRecords *g_ppRecords; mean g_ppRecords to be an array because an array should be defined as
type arrayname[size];
I tried allocating memory to g_ppRecords dynamically, but that’s not helping.
g_ppRecords = (pStudentRecord*) malloc(sizeof(pStudentRecord*)*(g_numRecords+1));
Observe that
pStudentRecordis typedef’d as a pointer to a structure. Pointers in C simply point to the start of a memory block, whether that block contains 1 element (a normal “scalar” pointer) or 10 elements (an “array” pointer). So, for example, the followingmakes
pcpoint to a piece of memory that starts with the character'x', while the followingmakes
spoint to a piece of memory that starts with"abcd"(and followed by a null byte). The types are the same, but they might be used for different purposes.Therefore, once allocated, I could access the elements of
g_ppRecordsby doing e.g.g_ppRecords[1]->firstName.Now, to allocate this array: you want to use
g_ppRecords = malloc(sizeof(pStudentRecord)*(g_numRecords+1));(though note thatsizeof(pStudentRecord*)andsizeof(pStudentRecord)are equal since both are pointer types). This makes an uninitialized array of structure pointers. For each structure pointer in the array, you’d need to give it a value by allocating a new structure. The crux of the problem is how you might allocate a single structure, i.e.Luckily, you can actually dereference pointers in
sizeof:Note that
sizeofis a compiler construct. Even ifg_ppRecords[1]is not a valid pointer, the type is still valid, and so the compiler will compute the correct size.