在C数组的大小 [英] size of array in c

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

问题描述

一个简单的问题是我的错误。
说我有主定义这样一个数组 INT ARR [5] 。现在,如果我还在里面主,我设置 INT I = sizeof的(ARR)/ sizeof的(ARR [0])然后我设置为5,但如果我通过数组作为​​函数参数和做同样的计算在此功能,我得到一个不同的数字。这是为什么?起初我以为它的,因为在一个函数改编是一个指针,但据我所知改编是一个指针里面主要的呢!

a simple question that bugs me. Say I have an array defined in main like so int arr[5]. Now, if I'm still inside main and I set int i = sizeof(arr)/sizeof(arr[0]) then I is set to be 5, but if I pass the array as a function parameter and do the exact same calculation in this function, I get a different number. Why is that? At first I thought its because in a function arr is a pointer, but as far as I know arr is a pointer inside main too!

另外,如果我做的非常类似的东西只有我动态初始化数组,我得到怪异的结果:

Also, if I do something very similar only I initialize the array dynamically, I get weird results:

int *arr = (int*) malloc(sizeof(int) * 5);
int length = sizeof(*arr) / sizeof(arr[0]);
printf("%d\n",length);

下面输出 1 。任何想法,为什么?
在此先感谢!

Here the output is 1. Any ideas why? Thanks in advance!

推荐答案

C数组并不存储自己的尺寸的任何地方,这样的sizeof()只适用于所预期的如果大小在编译时已知的方式。 malloc()函数是由编译器为任何其他功能处理,使的sizeof()不能告诉改编是一个数组,更不用说有多大它是。如果你需要知道数组的大小,你需要明确它传递给你的函数,既可以作为单独的参数,或者通过使用含有指针阵列和它的尺寸结构。

C arrays don't store their own sizes anywhere, so sizeof() only works the way you expect if the size is known at compile time. malloc() is treated by the compiler as any other function, so sizeof() can't tell that arr is an array, let alone how big it is. If you need to know the size of the array, you need to explicitly pass it to your function, either as a separate argument, or by using a struct containing a pointer to your array and its size.

这篇关于在C数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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