如何在 C 中获取动态数组的大小?

How to get dynamic array's size in 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) 因为它会给出第一个元素的大小。出于上下文目的,需要使用动态数组来扩展每个新数据的大小。

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

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

唯一的方法是将大小信息存储在某个地方,如本例所示:

typedef struct
{
    size_t size;
    int arr[];
}int_array_t;

int_array_t *alloc(size_t nelem)
{
    int_array_t *arr = malloc(sizeof(*arr) + nelem * sizoef(arr -> arr[0]));

    if(arr)
    {
        arr -> size = nelem;
    }
    return arr;
}