【发布时间】:2024-04-30 15:45:02
【问题描述】:
我正在学习 C 动态内存分配,但不明白为什么 malloc 或 calloc 没有分配为 struct 数组和 name char 数组指定的内存量。
代码示例:
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;
}
输出:
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
【问题讨论】:
-
sizeof不能给出动态分配内存的大小,只能给出指针的大小。您需要自己跟踪动态分配内存的大小。 -
它正在分配指定的数量。
标签: c printf malloc dynamic-memory-allocation sizeof