Reputation: 23830
Can sizeof
safely be used on an array that has been declared without an explicit size specified inside the square brackets, but which gets initialised in the declaration?
Consider the following code:
unsigned int arr[] = { 1, 2, 3 };
size_t bytes = sizeof arr;
If compiled on macOS with clang-800.0.42.1 without any special compiler flags, this yields the expected result of 12
.
But does the C standard (or any C standard, if they differ on this) guarantee this to be the case? Or do I have to declare it like unsigned int arr[3]
in order for it to be "sane"?
Upvotes: 0
Views: 772
Reputation: 18299
Yes, the standard guarantees that the array element count will be equal to the number of elements in the array initializer in case no size is specified. See C11 standard draft 6.7.9p22 and 6.7.9p25:
If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. The array type is completed at the end of its initializer list.
EXAMPLE 2 The declaration
int x[] = { 1, 3, 5 };
defines and initializes
x
as a one-dimensional array object that has three elements, as no size was specified and there are three initializers.
Upvotes: 8
Reputation: 148880
unsigned int arr[] = { 1, 2, 3 };
actually defines a complete array. The size of the array is known in this compilation unit and is n*sizeof(type) where n is the number of elements in the initialization list (here 3) and type is the underlying object type (here unsigned int
).
That means that sizeof(arr)
is defined in same scope as arr
and has the expected value.
What would be completely different would be extern int arr[];
. That would be a simple declaration that an array of that name will be provided in another compilation unit, but the compiler has no way to know its size. In that case using sizeof(arr)
will be an error.
Another example of mere declaration is
void func(int arr[]) {
...
}
Here again the compiler only knows that the function will receive an int array, but again cannot know its size. But here the compiler generates a pointer that will receive the address of the array and sizeof(arr)
is defined but is the size of that pointer and not the size of the original array.
Upvotes: 1