首页 > 解决方案 > 如何在 C 中获取动态数组的大小?

问题描述

我正在尝试使用sizeof获取C中动态数组的大小。我有结构并使其具有 10 个元素的数组。

struct date{
int day;
int month;
int year;
};

void main(){
struct date *table;

table = (struct date*) malloc(sizeof(struct date) * 10);
}

因此,当我尝试使用 sizeof 获取大小时,我得到 8 而不是 120(因为结构的大小是 12)。

printf("%d, sizeof(table)); 
output is 8

我没有将其设为动态数组,而是将其更改为静态数组以查看会发生什么,它给出了 120。所以我不明白问题出在哪里。我知道我不能说 sizeof(*table) 因为它会给出第一个元素的大小。出于上下文目的,需要使用动态数组来扩展每个新数据的大小。

标签: arrayscpointersdynamic-memory-allocation

解决方案


在您的示例table中有 type struct date *。因此,当您在其上使用sizeof运算符时,您将获得指针的大小。

没有可移植的方法来确定指向已分配内存的指针指向多少可用空间。您需要自己跟踪。


推荐阅读