带指针变量的 Sizeof 运算符

时间:2021-04-25 04:53:19

标签: c++ sizeof

我知道 x = soup.select('tr[itemprop="backwardReferences"]') y = soup.select('td[itemprop="title"]') # this line gives all the titles in the document not particularly under the patent citations print(y) print(y) 运算符返回 C/C++ 中任何给定类型的大小。在 C 风格的数组中,数组的名称是一个指针本身,指向数组的第一个元素。例如,在 sizeof 中,int arr[2] = {2, 3} 将产生 *arr。那么为什么2运算符不返回指针变量的大小,而是返回数组在内存中占用的总大小。

查看此代码:

sizeof

输出:40 个字节(给定 #include <iostream> using namespace std; int main() { int arr[10]; cout << sizeof (arr); return 0; } 需要 4 个字节)

我想在这段代码中问的是,即使 int 只是一个指针,那么 sizeof 如何返回这个数组占用的整个大小?

我自己写了 arr 来理解它:

sizeof

输出:8 个字节(给定的指针变量占用 8 个字节)

这段代码现在只打印指针变量的大小。我是否遗漏了有关 #include <iostream> using namespace std; template <typename T> size_t my_sizeOf(T var) { return (char *) (&var + 1) - (char *) (&var); } int main() { int arr[10]; cout << my_sizeOf(arr); return 0; } 运算符的一些关键点?

2 个答案:

答案 0 :(得分:4)

#include <iostream>
using namespace std;

int main()
{
    int arr[10];

    cout << sizeof (arr); // 40
    return 0;
}

arr 只是一个指针。它是一个数组,大小为 10。数组在传递给函数时可以衰减为指针,但类型 int[10]int* 是不同大小的不同类型。

请注意,如果我们将其强制为指针,则会得到您期望的结果。

#include <iostream>
using namespace std;

int main()
{
    int arr[10];

    cout << sizeof ((int*)arr); // 8 (on 64-bit systems)
    return 0;
}

另一方面,如果您动态分配一个数组(您不应该这样做;99% 的情况下,std::vector 更好更智能),那么您必须存储它在一个指针中,而不是一个数组变量。

#include <iostream>
using namespace std;

int main()
{
    int* arr = new int[10];

    cout << sizeof (arr); // 8 (on 64-bit systems)
    delete[] arr;
    return 0;
}

特别要注意的是,sizeof 不是一个函数,并且不计算它的参数。这是一个特殊的关键字,它只使用其参数的类型。

答案 1 :(得分:3)

在 C++ 中,int arr[10]; 的声明将 arr 声明为 int[10] 类型,即一个包含 10 个 int 的数组。由于数组的大小是 arr 类型的一部分,因此 sizeof 运算符知道实际大小是多少。

在您的函数 my_sizeOf 中,您将 arr 衰减到函数参数中的一个指针,因此您获得的是指针的大小而不是数组的大小。编写函数的正确方法是

template <typename T, size_t N>
size_t my_sizeOf(T (&)[N])
{
  return N;
}
相关问题