Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialisation of char array to string value, are the uninitialised indices set to null?

Tags:

If I have the following:

char test[10] = "#"; 

Is test[1] through test[9] guaranteed to be \0? Or is only test[1] guaranteed to be \0?

like image 877
Mark Ingram Avatar asked Aug 18 '14 11:08

Mark Ingram


People also ask

How do you initialize a char array to null?

You can't initialise a char array with NULL , arrays can never be NULL . You seem to be mixing up pointers and arrays. A pointer could be initialised with NULL . char str[5] = {0};

What is in an uninitialized char array?

Uninitialized spaces are filled as zeroes. But, that means, integer zero, or the character whose ASCII value is zero (which, in fact, is '\0' ).

How do you initialize a char array in C++?

In C++, when you initialize character arrays, a trailing '\0' (zero of type char) is appended to the string initializer. You cannot initialize a character array with more initializers than there are array elements. In ISO C, space for the trailing '\0' can be omitted in this type of information.

What is the default value of char array in C?

For char arrays, the default value is '\0' . For an array of pointers, the default value is nullptr . For strings, the default value is an empty string "" . That's all about declaring and initializing arrays in C/C++.


1 Answers

This definition

char test[10] = "#"; 

is equivalent to

char test[10] = { '#', '\0' }; 

That is two elements of the array are initialized explicitly by the initializers. All other elements of the array will be zero initialized that is implicitly they will be set tto '\0'

According to the C++ Standard (section 8.5.2 Character arrays)

3 If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized (8.5).

like image 53
Vlad from Moscow Avatar answered Sep 26 '22 09:09

Vlad from Moscow