1

If we declare an array of characters in C

Ex:

char label[] = "Hello";

We will have an array in memory which looks like this

--------------------------
| H | e | l | l | o | \0 |
--------------------------

where the extra null byte is added at the end of the array.

Scenario 1:

char label[10] = "Hello";

------------------------------------------ 
| H | e | l | l | o | \0 |   |   |   |   | 
------------------------------------------ 

where it will have an extra 4 unused locations.

Scenario 2:

Here if we have exactly a string with 10 characters, will the \0 (null byte) still be added, which makes the char array to hold 11 characters?

char label[10] = "0123456789";

----------------------------------------- 
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 
----------------------------------------- 

              OR

----------------------------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | \0 |
----------------------------------------------
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
naveenath
  • 99
  • 1
  • 7
  • 1
    With `label[10]` you define the array to have exactly 10 symbols. So, no 11th symbol (`\0`) can be added by the compiler. Typically, you get a warning that the string initialization is too long for the array. – Hartmut Pfitzinger Jul 17 '16 at 07:59
  • 1
    Just as an FYI, C++ doesn't allow you to initialize `char label[10]` with more than 9 characters (it adds a null byte for the tenth, of course). C doesn't have that rule (but you couldn't add an explicit 11th character to the initializer). – Jonathan Leffler Jul 17 '16 at 08:09

1 Answers1

2

Your understanding is almost correct:

char label[10] = "Hello";

will initialize a 10 byte char array with | H | e | l | l | o |\0|\0|\0|\0|\0|.

Whereas for the last case:

char label[10] = "0123456789";

the array is also 10 char long, initialized with | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |. This array is therefore not null terminated and should not be used as a C string.

chqrlie
  • 131,814
  • 10
  • 121
  • 189