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

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

问题描述

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

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)

我正在学习如何在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查看类型,但是您不能以任何方式从malloc的结果中获得完整的数组类型(具有指定大小的数组类型,如类型int[5]),并且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天全站免登陆