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

查看:53
本文介绍了在不使用 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 数组的指针.

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

[1]的意思是加上指向的东西的大小",是一个100个ints的数组.

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天全站免登陆