在 C 中查找 malloc() 数组长度? [英] Find malloc() array length in C?

查看:78
本文介绍了在 C 中查找 malloc() 数组长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何找到sizeof(指向数组的指针)

我正在学习如何在 C 中创建动态数组,但遇到了一个我无法弄清楚的问题.

I'm learning how to create a dynamic array in C, but have come across an issue I can't figure out.

如果我使用代码:

int num[10];
for (int i = 0; i < 10; i++) {
    num[i] = i;
}
printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0]));

我得到输出:

sizeof num = 40
sizeof num[0] = 4

这是我期望发生的事情.但是,如果我像这样分配数组的大小:

This is what I'd expect to happen. However if I malloc the size of the array like:

int *num;
num = malloc(10 * sizeof(int));
for (int i = 0; i < 10; i++) {
    num[i] = i;
}
printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0]));

然后我得到输出:

sizeof num = 8
sizeof num[0] = 4

我很好奇为什么使用定长方法时数组的大小是40,而使用malloc()时却不是.

I'm curious to know why the size of the array is 40 when I use the fixed length method, but not when I use malloc().

推荐答案

在第二种情况下,num 不是数组,是指针.sizeof 为您提供指针的大小,在您的平台上似乎是 8 个字节.

In the second case, num is not an array, is a pointer. sizeof is giving you the size of the pointer, which seems to be 8 bytes on your platform.

没有办法知道动态分配的数组的大小,您必须将其保存在其他地方.sizeof 查看类型,但不能从结果中得到完整的数组类型(指定大小的数组类型,如int[5]类型)malloc 以任何方式,并且 sizeof 参数不能应用于不完整的类型,例如 int[].

There is no way to know the size of a dynamically allocated array, you have to save it somewhere else. sizeof looks at the type, but you can't obtain a complete array type (array type with a specified size, like the type int[5]) from the result of malloc in any way, and sizeof argument can't be applied to an incomplete type, like int[].

这篇关于在 C 中查找 malloc() 数组长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆