Please see the code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[10] = {'L','e','s','s','o','n','s'}; // did not add `\0`
char c;
for (int i = 0; name[i] != '\0'; i++)
{
c = name[i];
printf("%c", c);
}
return 0;
}
I did not give \0
at the end, but still it works.
My question: Is \0
added automatically in the above case?
EDIT: What happens in these cases:
char name[7] = {'L','e','s','s','o','n','s'};
char name[8] = {'L','e','s','s','o','n','s'};
I apologize for editing the question.
In C, partially initialized arrays of any type are 0-initialized for the rest. So,
int foo[5] = {1, 2, 3};
will initialize foo
with {1, 2, 3, 0, 0}
. So, when you don't add '\0'
to the end, not only will the end be '\0'
(assuming the array is large enough to fit it), but all remaining elements of the array will be '\0'
.
If your array isn't large enough to fit the null terminator, then it won't be added, nor should the value even matter. Reading past the end of an array is undefined behavior, which can lead to segfaults, garbage data, or worse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With