Arrays with 0 elements

Is an array with 0 elements the same as an unallocated pointer?

Is int arr[0]; same as int* arr; ?

Edit: what if I did something similar to this:

 int x[0]; int* const arr = x; 

I tried this code and compiled it. As far as I know, both x and arr should point to the same place in memory. What is the difference in this case?

+8
c ++ arrays pointers
source share
3 answers

Not at all.

In the case of arr [0], arr has a well-defined address.

In the case of * arr, arr is simply not initialized.

After your EDIT, where you initialize const arr using the array defined earlier: there simply will be no differences in the contents of the variables, but in the actions that you are allowed to perform on them.

+13
source share

A locally declared zero-length array is illegal in C ++, so it does not match an unallocated pointer.

+4
source share

The argument of zero length indicates a specific address, the beginning of the array. After the array finishes, you will have undefined data, in this case, at the address it points to.

 int arr[0]; int* ptr; // arr is a reliable value; // *arr is not; // ptr is not; 

One way this is useful: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Zero-Length.html

0
source share

All Articles