I'm trying to access the next element in dynamically allocated by adding the size of placeholder array to the first element. Size of placeholder array is 4 bytes, so if I add 4 bytes to it first element with address 2147549788, I should be looking at next memory location 2147549792. But, instead I'm looking at an address in 16 bytes 2147549804. If I read the address of array elements directly I get the right address. Wondering why adding size of placeholder gives different results ? Also, if I access the location of second element outside the for loop, the location is off by another 16 bytes i.e 2147549820
#include "stdio.h"
#include "time.h"
#include <stdlib.h>
#include <string.h>
typedef struct Section {
int numOfStudents;
} Section;
typedef struct School {
int schoolId;
Section sections[1]; //placeholder
} School;
int main(void)
{
School *schoolA_p;
Section section1;
int sizeOffset = 0;
int i,sectionSize;
int sizeOfSchool = sizeof(School) - sizeof(Section) + (sizeof(Section)*2);
schoolA_p = (struct School *) malloc(sizeOfSchool);
for(i=0;i<2;i++)
{
sectionSize = sizeof(Section);
printf("\nsize of section = %d\n", sizeof(Section));
printf("Number of bytes to add to first element to access the next element = %d\n", sizeOffset);
printf("In Loop Location of schoolA_p->sections[%d]= 0x%lx\n",i, &(schoolA_p->sections[0]) + sizeOffset);
sizeOffset += sectionSize;
}
printf("\n Location of schoolA_p->sections[0]= 0x%lx\n",&(schoolA_p->sections[0]));
printf("\n Location of schoolA_p->sections[1]= 0x%lx\n",&(schoolA_p->sections[1]));
printf("\n Outside of lopop Location of schoolA_p->sections[0]= 0x%lx\n", &(schoolA_p->sections[0])+ sizeOffset);
free(schoolA_p);
return 0;
}
%pto print a pointer, which should be cast tovoid*such asprintf("%p",(void*)ptr)