C 中的数组长度 [英] array_length in C

查看:34
本文介绍了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;

但是当我做的时候

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

在主函数中,返回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.

上述代码的问题在于,当您这样做时:

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 位系统,则函数内部的 sizeof(a)/sizeof(int) 总是会得到 2,因为指针将是 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.)

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

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