I'm learning C dynamic memory allocation and can't figure out why malloc
or calloc
are not allocating the amount of memory specified for the struct array, nor for the name char array.
Code example:
struct spaceShip{
long long int distance; // 8 bytes
int numParts; // 4 bytes
char *name; // 1 byte
}; // 13 bytes total
int main (int argc, char *argv[]){
int amount=10;
struct spaceShip *spaceShipArray;
printf("size of struct spaceShip = %d bytes\n", sizeof(struct spaceShip));
spaceShipArray = malloc(amount * sizeof(*spaceShipArray));
printf("size of spaceShipArray = %d bytes\n", sizeof(*spaceShipArray));
spaceShipArray[0].name = malloc(100 * sizeof(char));
printf("size of name char array = %d \n", sizeof(spaceShipArray[0].name));
free(spaceShipArray);
return 0;
}
Output:
size of struct spaceShip = 16 bytes //I guess because of the pagination mechanism it takes more?
size of spaceShipArray = 16 bytes // not ok. should be 160
size of name char array = 4 // not ok. should be 100