search

Home  >  Q&A  >  body text

c++ - c中隐式定义数组不指定大小会怎么样?

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

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中文网2806 days ago654

reply all(5)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 13:36:33

    @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;
    }

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:36:33

    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;  // 越界访问,是未定义行为。不会改变数组大小。

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:36:33

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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:36:33

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

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:36:33

    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

    reply
    0
  • Cancelreply