简体   繁体   English

C ++空数组大小

[英]C++ empty array size

I initialized an array in three different ways (either on heap or on stack), but contrary to my expectation, there appears to be two different values for their size. 我用三种不同的方式(在堆上或在堆栈上)初始化了一个数组,但与我的预期相反,它们的大小似乎有两个不同的值。 I don't understand why. 我不明白为什么。

int asd[0];    
sizeof(asd);   //ouput 0;   

int asd={};
sizeof(asd);    //output 4;

int *asd=new int[0];
sizeof(asd);    //output 4;

Since an array name is a pointer to an allocated memory block and as the size of a pointer is 4, I consider that outputs 2 and 3 are correct. 由于数组名称是指向已分配存储块的指针,并且指针的大小为4,因此我认为输出2和3是正确的。

But what I don't understand is why the output 1 is not showing size 4. 但是我不明白的是为什么输出1没有显示大小4。

The last two of your examples are not arrays; 您的最后两个示例不是数组;

The first is: int asd[0] is defining an array of size 0, which is not allowed. 第一个是: int asd[0]定义了一个大小为0的数组,这是不允许的。

If the expression is a constant expression, it shall have a value greater than zero. 如果表达式是一个常量表达式,则其值应大于零。

The second: int asd={}; 第二个: int asd={}; is int using aggregate initializaion. 使用汇总初始化int The size of int 4 bytes. int 4字节的大小。

The third: int *asd=new int[0]; 第三个: int *asd=new int[0]; is a pointer of type int pointing to a dynamically allocated memory. int类型的指针,指向动态分配的内存。 The size of the pointer is 4 bytes (2^32 addresses). 指针的大小为4 bytes (2 ^ 32个地址)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM