Why does int a[5] = {1,2,3,4,5,6} give a warning while int a[5] =
{1,2,3,4,5}; a[5] = 6; does not?
The assignment gives you a warning because you know the size of the variable in the initialization statement, and it is obviously violating the size of your declaration. You don't have the size of the array from a
in the line a[6] = 6
, so for the compiler it seems ok. Of course the level of warnings change from compiler to compiler, and for some compilers you can specify extra warnings.
For example, using gcc, you could use the flags -Wextra
and -Wall
to get a lot of warnings. Receiving warnings is a good thing, because the compiler helps you to find possible caveats without needing to debug your code. Of course, they are only good if you fix them :-)
Is it a good practice to do this when I initially declared the array
size to be 5?
It is never a good practice to assign an integer to a place in memory that you didn't declare - you can't be sure where this value is being written, and it can be overwriting another variable, or worse, partially overwriting some other variable or the stack. Since this kind of stuff is different from compiler to compiler, as @PascalCuoq pointed out, it is called undefined behavior, and is something you want to avoid at all costs. Of course, since it is undefined, it can happen that your program will execute just fine after this declaration, yet it is a very poor practice.
However, there is nothing wrong with initializing an array with fixed size, if it will not change. You should avoid magic numbers and use constants instead, like MAX_NUMBER_OF_PERMUTATIONS
or CURRENCIES_SIZE
, for instance.
Can I declare it like this: int a[]?
Declaring it as int a[]
is a shorthand when you are initializing a fixed array and the compiler can specify the number of elements. For example:
int a[] = {1,2,3}; //this is good
int b[3] = {1,2,3}; //same from above
In the past it was usual declare int a[];
however it don't works in every compiler, so should be avoided. (Thanks @PascalCuoq for pointing this out)
What if I don't know the size of my array?
If you don't know the size of your array, you should declare it as a pointer, like int * a
and manage the memory yourself using malloc
, realloc
, calloc
and similar system calls. Please do a good job and learn about free
too - the world will thank you later. You should read about pointers instead of arrays if you are looking for dynamic memory allocation.