arrays - 如何在 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
中有 type struct date *
。因此,当您在其上使用sizeof
运算符时,您将获得指针的大小。
没有可移植的方法来确定指向已分配内存的指针指向多少可用空间。您需要自己跟踪。
推荐阅读
- c# - 如何在C#中删除2个十进制值之后的字符
- python - 为什么在 Python 中第二次输入后我的字典的值没有更新?
- java - 为什么它不被视为多重继承,而所有类都先从 Object 类扩展,然后再扩展其他类
- java - 如何在没有中断的情况下停止while循环并在java中退出
- julia - Julia:彩条的牛虻大小
- java - 设置 bean 属性时找不到具有逻辑名称的列
- discord.js - 为什么这个机器人在“user.hasPermission()”上失败了?
- python - 在管理页面上添加表时 Django 出错
- excel - 合并来自已关闭工作簿的数据 adodb 方法
- unity3d - Sing app bundle with lost keystore 如何更新?