array_length用C [英] array_length in C

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

问题描述

我写了一个array_length功能是这样的:

I wrote an array_length function like this:

int array_length(int a[]){
    return sizeof(a)/sizeof(int);
}

不过它返回2,当我做

However it is returning 2 when I did

unsigned int len = array_length(arr);
printf ("%i" , len);

在那里我有

int arr[] = {3,4,5,6,1,7,2};
int * parr = arr;

但是,当我只是做

But when I just do

int k = sizeof(arr)/sizeof(int);
printf("%i", k);

在主函数,它返回7。

in the main function, it returns 7.

什么是写array_length功能的正确方法,如何使用它?

What is the correct way to write the array_length function and how do I use it?

推荐答案

计算阵列的长度,在C,是有问题的最好的。

Computing array lengths, in C, is problematic at best.

与code以上的问题,就是当你做的:

The issue with your code above, is that when you do:

int array_length(int a[]){ 
    return sizeof(a)/sizeof(int); 
} 

你真的只是传递一个指针为A,所以的sizeof(A)的sizeof(INT *)。如果你是一个64位系统上,您总能获得2 的sizeof(A)/ sizeof的(INT)里面的功能,因为该指针将是64位。

You're really just passing in a pointer as "a", so sizeof(a) is sizeof(int*). If you're on a 64bit system, you'll always get 2 for sizeof(a)/sizeof(int) inside of the function, since the pointer will be 64bits.

您可以(可能)做到这一点作为一个宏而不是一个函数,而是有它自己的问题......(它彻底内联这一点,所以你得到同样的行为,作为你的 INT K = ... 块,虽然。)

You can (potentially) do this as a macro instead of a function, but that has it's own issues... (It completely inlines this, so you get the same behavior as your int k =... block, though.)

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

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