Initialization of arrays in C

2020-04-16 05:13发布

问题:

In C, I have read that half-initialized arrays will be filled with zeros for the rest of the elements (irrespective of integer or char arrays).

E.g.:

int arr[10] = {3};

arr[4] will be 0 if initialized and a junk value if not initialized.

My question is, will the above work for all C compilers (or) this appending of zeros might occur or not occur depending on the compiler option? I am working in Code composer studio (TI's IDE). I want to ensure that this will work for all cases and all compilers.

回答1:

The behaviour is specified by the C Standard. But if you are worried about the behaviour of your specific compiler, why not write a test?



回答2:

This is according to the C standard, and any compiler following the C standard must do this. However, not all compilers are 100% standard compliant, and you'll have to check if yours does this or not, if you're unsure.



回答3:

Variables, located in data segment (global and unit scope), are automatically initialised to all zeros.

Stack variables (function and block scope) are filled with garbage unless explicitly initialised, even partially initialised. In case of partial initialisation, reminder is zeroed.

That's by the C standard and all compilers must adhere to it.



回答4:

This should work irrespective of which compiler you are using.



回答5:

If you want to be sure that your code will work with all compilers you should initialize all your array elements just like it:

int arr[10] = {3,0,0,0,0,0,0,0,0,0};

If the number of elements of your array is too high (100 or 10000) the best solution becomes to initialize it dynamicaly at the runtime.



回答6:

It is dependent on the design of the compiler. Normally compilers support it and some may support via some flags during compilation or other options. Some may not support it. It is better to check with the concerned compiler support regd the compatibility with C standard. I think Code Composer Studio IDE(TI DSP processors) support group might give you the exact answer.

Karthik Balaguru



回答7:

The language spec specifies default behavior, however not all compilers implement the defined behavior. A good example of this is that Visual Studio 2008 is the first version of the Microsoft C/C++ compiler that will call the default constructor on uninitialized elements in an array which has been the defined behavior of array initialization since at least the C++ 98 spec.

If you are worried about how your code will behave running on multiple compilers it is better to be safe than sorry and explicitly initialize all values.