如何在不使用sizeof的情况下在C/C++中查找数组的大小?

我们可以使用sizeof运算符找到数组的大小,如下所示。

null
// Finds size of arr[] and stores in 'size'
int size = sizeof(arr)/sizeof(arr[0]);

不使用sizeof运算符也可以这样做吗?

方法1(编写我们自己的sizeof) 给定一个数组(你不知道数组中元素的类型),在不使用sizeof运算符的情况下求数组中元素的总数?

一种解决方案是编写我们自己的sizeof操作符(参见 (详情请参阅)

// C++ program to find size of an array by writing our
// sizeof
#include <bits/stdc++.h>
using namespace std;
// User defined sizeof macro
# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int size = my_sizeof(arr)/my_sizeof(arr[0]);
cout << "Number of elements in arr[] is "
<< size;
return 0;
}


输出:

Number of elements in arr[] is 6

方法2(使用指针破解) 与上述解决方案相比,以下解决方案非常简短。数组A中的元素数可以通过表达式计算出来

int size = *(&arr + 1) - arr;

// C++ program to find size of an array by using a
// pointer hack.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int size = *(&arr + 1) - arr;
cout << "Number of elements in arr[] is "
<< size;
return 0;
}


输出:

Number of elements in arr[] is 6

这是怎么回事? 在这里,指针算法发挥了作用。我们不需要显式地将每个位置转换为字符指针。

&arr ==> Pointer to an array of 6 elements.
         [See this for difference between &arr
          and arr]   

(&arr + 1) ==> Address of 6 integers ahead as
               pointer type is pointer to array
               of 6 integers.

*(&arr + 1) ==> Same address as (&arr + 1), but 
                type of pointer is "int *".

*(&arr + 1) - arr ==> Since *(&arr + 1) points 
                   to the address 6 integers
                   ahead of arr, the difference
                   between two is 6.          

本文由 Nikhil Chakravartula 来自海得拉巴JNTUH工程学院。如果你喜欢GeekSforgeks,并且想贡献自己的力量,你也可以写一篇文章,然后把你的文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享