在不使用sizeof的情况下查找数组的大小 [英] Find size of array without using sizeof

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

问题描述

我正在寻找一种无需使用sizeof即可在C中查找数组大小的方法,并且发现了以下代码:

I was searching for a way to find the size of an array in C without using sizeof and I found the following code:

int main ()
{
    int arr[100];
    printf ("%d\n", (&arr)[1] - arr);
    return 0;
}

任何人都可以向我解释一下它是如何工作的吗?

Can anyone please explain to me how is it working?

推荐答案

&arr是指向100个int s数组的指针.

&arr is a pointer to an array of 100 ints.

[1]的意思是添加所指向对象的大小",它是100个int s的数组.

The [1] means "add the size of the thing that is pointed to", which is an array of 100 ints.

所以(&arr)[1]arr之间的差是100 int s.

So the difference between (&arr)[1] and arr is 100 ints.

(请注意,此技巧仅在sizeof仍然可以使用的地方有效.)

(Note that this trick will only work in places where sizeof would have worked anyway.)

这篇关于在不使用sizeof的情况下查找数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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