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

📅  最后修改于: 2021-05-26 00:39:37             🧑  作者: Mango

我们可以使用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 
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 
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.          
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”