c++ - c中隐式定义数组不指定大小会怎么样?
PHP中文网
PHP中文网 2017-04-17 13:34:33
0
5
643

我在申明的时候是这样写的:

int a[] = {};
cout<<sizeof(a)<<endl;
a[0] = 12;
cout<<sizeof(a)<<endl;
cout<<a[0]<<endl;

两次输出数组总字节都是0,两个问题:
1.为什么还能对a[0]赋值?
2.为什么对a[0]赋值之后,数组的大小还是0?

PHP中文网
PHP中文网

认证0级讲师

reply all(5)
Peter_Zhu

@Fallenwood This is not certain, it may be evaluated at runtime.

#include <stdio.h>

void test(const int t)
{
    int p[t];
    printf("sizeof(p) = %u\n",sizeof(p));
}

int main() {
    unsigned int x;
    scanf("%u",&x);
    test(x);
    return 0;
}
大家讲道理

When defining an array, if an initial value is provided, the size of the first dimension of the array can be omitted. If the size of the first dimension is omitted, the size of the array is the number of initial values. For example definition:

int a[] = {};

The first dimension is omitted, the initial value is provided, and the number of initial values ​​is 0, which means the size of the array is also 0.

Why can we still assign a value to a[0]? Why is the size of the array still 0 after assigning a[0]?

a[0] = 12;

Accessing an array out of bounds is undefined behavior. It is the same as the following example:

int a[5];
a[2333] = 666;  // 越界访问,是未定义行为。不会改变数组大小。
洪涛

To add to the answer above, the sizeof operator is determined during compilation

大家讲道理

c/c++ does not check array subscripts, you will be responsible for the consequences

迷茫

int a[] = {}; The array size is zero, which means there is only one array of a, but there is no memory space. Of course, the first address a of the array also points to an unknown place. The assignment of
a[0]=12; is to store 12 into the first element of the array, which is the first address. This is undefined behavior and may cause program errors

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template