为什么的sizeof(param_array)为指针的大小? [英] Why sizeof(param_array) is the size of pointer?

查看:110
本文介绍了为什么的sizeof(param_array)为指针的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个数组的长度,说 int数组[] = {1,2,3,4} 。我用的sizeof 来做到这一点。

I want to get the length of an array, say int array[] = {1, 2, 3, 4}. I used sizeof to do that.

int length(int array[])
{
     return sizeof(array) / sizeof(int);
}

int main()
{
    int array[] = {1, 2, 3, 4};
    printf("%d\n", length(array)); // print 1
    printf("%d\n", sizeof(array) / sizeof(int)); // print 4
}

那么,为什么的sizeof(阵列)函数长度返回的指针大小阵列?但在功能,它的工作原理。

So, why the sizeof(array) in function length returns the pointer size of array? But in function main, it works.

和,我应该怎么修改长度函数获得一个数组的长度?

And, how should I modify the length function to get an array's length?

推荐答案

一个特殊的C规则,说,对函数参数数组类型的调整的到指针类型。这意味着:

A special C rule says that for function parameters, array types are adjusted to pointer types. That means:

INT长度(int数组[]);

等同于

INT长度为(int *数组);

所以,当你计算的sizeof 你实际上是计算指针的大小的阵列。

So when you compute the sizeof the array you are actually computing the size of the pointer.

(C99,6.7.5.3p7)类型的数组的参数作为的声明,应调整为合格指向类型,这里的类型修饰符
          (如果有的话)的范围内[和]数组类型派生的规定。

(C99, 6.7.5.3p7) "A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation."

这篇关于为什么的sizeof(param_array)为指针的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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