how to initialize array(C / C++)


case 1, 2, 3
int array[5] = { 0 };  VS int array[5] = { 0, };
and
memset(array, 0, 5);

case 1, 
int array[5] = { 0 };
=  array[0] = 0
    array[1] ~ array[4] = not initialized ? NO!
=  array[0] ~ array[4] = 0  Of Course, OK!

case 2,
int array[5] = { 0, };
=  array[0] ~ array[4] = 0  OK!

result :

int array[5]={0,1,2};
and
int array[5]={0,1,2,};

The elements array[4] and array[5] are automatically initialized to 0 in this case. 

the compiler take care of the rest(zero-initialize).


case 3,
memset(array, 0 , 5);

I don't recommend this case.
because you need to #include a special header(#include <cstring>).
and this case, all element is initialized to number 0.
so, you can't set to the value of 1 element and 2, ... .

No comments:

Post a Comment

Apartment Buying Guide 2025: Shocking Red Flags You Should NEVER Ignore!

 🏙️ Apartment Buying Guide 2025: Shocking Red Flags You Should NEVER Ignore! 🚨 Are you thinking about buying an apartment in 2025? 🏢  It’...