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[] = {}; 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
@Fallenwood This is not certain, it may be evaluated at runtime.
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:
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.
Accessing an array out of bounds is undefined behavior. It is the same as the following example:
To add to the answer above, the
sizeof
operator is determined during compilationc/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