There are two ways (at least) to initialize an array in C. What is the difference between
int array[] = {1,2,3,4,5,6,7,8,9} ;
and:
int array[100] = {1,2,3,4,5,6,7,8,9} ;
I do not mean in means of memory allocation. Perhaps the thing that provoked this question would be useful so as to understand my question.
I wanted to get the length of an int array by iterating trough it. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int array[] = {1,2,3,4,5,6,7,8,9} ;
int i = 0 ; // i is length
while( array[i] ) {
printf("%d\n" , array[i] ) ;
i++ ;
}
printf("%d\n" , i) ;
And I noticed that when I used array[] the length sometimes was wrong because of some sort of overflow , but when I used array[100] the length was always right. What is the difference between these two? Has it got something to do with '\0' character ?
When you create the array without specifying its size the compiler infers it from the initializer (in this case, the length would be 9). The memory locations immediately after the array have unspecified contents since noone bothered giving them specific values, and that's why you get the "overflow" behavior -- this is technically undefined behavior, but the result is a very common way for the compiler vendor to implement "undefined".
When you explicitly specify the size the compiler initializes the array with as many elements as you have provided, then fills the remaining space with zeroes.
In both cases the behavior is according to the standard.
You can programmatically get the size of the array with the sizeof
operator. So in this case, you can do sizeof(array)/sizeof(int)
to get the actual size. The sizeof operator is handled by the compiler, which will insert the correct size constant at compile time.
Note that iterating through the array until you get to a false result is undefined behavior and should not be done.
Pertaining to your original question, @Jon is correct; either array size specifier is correct and will yield the same results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With