In C the string is always terminated with a \0
character, so the length of the string is the number of characters + 1. So, in case you need to initialise a string of 12 characters, you must "allow one element for the termination character" (from p.221, "Beginning C", Horton).
All right, let's try
#include <stdio.h>
int main(void)
{
char arr1[12] = "Hello world!";
char arr2[] = "Hello world!";
printf("\n>%s< has %lu elements", arr1, sizeof(arr1) / sizeof(arr1[0]));
printf("\n>%s< has %lu elements", arr2, sizeof(arr2) / sizeof(arr2[0]));
return 0;
}
outputs
>Hello world!< has 12 elements
>Hello world!< has 13 elements
Why the C complier allowed me to create a fixed size array arr1
without a \0
character and added \0
when I asked for a variable sized array arr2
?