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

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

问题描述

一个让我烦恼的简单问题.假设我在 main 中定义了一个数组,就像 int arr[5].现在,如果我仍然在 main 中并且我设置 int i = sizeof(arr)/sizeof(arr[0]) 那么我被设置为 5,但是如果我将数组作为函数参数并在此函数中进行完全相同的计算,我得到了不同的数字.这是为什么?起初我以为是因为在函数中 arr 是一个指针,但据我所知 arr 也是 main 中的一个指针!

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 无法判断 arr 指向数组的第一个元素,别说有多大了.如果您需要知道数组的大小,则需要将其显式传递给您的函数,或者作为单独的参数,或者使用包含指向数组及其大小的指针的结构.

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 points to the first element of 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天全站免登陆