Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if the amount of characters that are entered into your character array is less than the amount of spaces you specified

char ch_arry[20] = { S, A, L, L, Y};
printf( "%s", ch_arry[] );

Will it fill the end of the array with null characters?

like image 433
Demarcus Sales Avatar asked Dec 24 '22 16:12

Demarcus Sales


2 Answers

From the C Standard (6.7.9 Initialization)

19 The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;151) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

And

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

So if you have a declaration like this

char ch_arry[20] = { 'S', 'A', 'L', 'L', 'Y'};

then all elements of the array that are not initialized explicitly will be initialized implicitly with zeroes.

like image 112
Vlad from Moscow Avatar answered Dec 26 '22 05:12

Vlad from Moscow


The remaining 15 characters are set to \0. This is a useful feature of C.

Note that you need to use

char ch_arry[20] = { 'S', 'A', 'L', 'L', 'Y'};

unless you have some insane macro trickery, and

printf("%s", ch_arry);
like image 32
Bathsheba Avatar answered Dec 26 '22 04:12

Bathsheba