【发布时间】:2017-09-22 16:39:46
【问题描述】:
这个问题是Declaring array of int的跟进
考虑以下程序:
#include <iostream>
#include <string>
int main()
{
int x[10];
std::cout << sizeof(x) << std::endl;
int * y = new int [10];
std::cout << sizeof(y) << std::endl;
//delete [] y;
}
sizeof(x) 打印 40(总大小),sizeof(y) 打印 8(指针大小)
它看起来很有趣,对我来说int x[10] 与y 没有什么不同,只是它位于堆栈中。 c++ 究竟在哪里存储了x 的大小? c++ 是否从堆栈中获取它?还是将固定大小的数组视为内部具有大小的结构?
【问题讨论】:
-
它根本不存储它。如果您需要,请改用
std::array<int,10>。 -
它不(存储大小),编译器知道
x的完整类型,其中包括数组的大小。y只是一个指针(不是数组),所以编译器就知道它了。另请注意:sizeof是在编译时而非运行时评估的。 -
@user0042,即使
std::array也不存储大小。至少我希望实现不会那样做。 -
在固定大小数组的情况下,比如问题中的x[10],编译器将大小“存储”在编译后的代码中,比如sizeof(x)最终作为一个常量编译代码中的 40,因为正如 Richard Critten 所指出的,sizeof() 是在编译时评估的。
-
它是类型的一部分。
int[10]与int[8]是不同的类型。编译器知道这个信息,所以它可以得到它的大小。
标签: c++ arrays memory-management