+ 1

Is the number of elements necessary?

In the C lessons, arrays are always defined like this: int x[3] = {0, 1, 2} Is it possible to define them like this so that length doesn't matter: int x[] = {0, 1, 2}

23rd Mar 2018, 9:19 PM
Galen Schick
Galen Schick - avatar
2 odpowiedzi
+ 1
The more important question is: Why would you want this functionality (except when initialising a string, which you're not doing)? It is _terrible_ practice because it makes code less readable and will cause compiler warnings (maybe even errors on some older ones). Rather use #define to define the array size if you may change it later. Or, _if you want a dynamic array_, use malloc/calloc, memcpy, and free along with pointers.
23rd Mar 2018, 10:06 PM
non
0
The arrays like this x[] are allowed as these get their limits on runtime, after checking the biggest index that is used in code. Hence allowed, but better not have a hole in them i.e int x[]; x[0]=1; x[1]=2; x[99]=3;
23rd Mar 2018, 9:24 PM
Saad
Saad - avatar