个性化阅读
专注于IT技术分析

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

点击下载

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

//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(使用指针hack)

与上述解决方案相比, 以下解决方案非常简短。数组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.

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

赞(0)
未经允许不得转载:srcmini » 如何在不使用sizeof的情况下在C/C++中查找数组的大小?

评论 抢沙发

评论前必须登录!