I have the following code.
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000
int main()
{
int i;
char s[MAXLINE];
for (i = 0; i < 20; ++i) {
s[i] = i + 'A';
printf("%c", s[i]);
}
printf("\nstrlen = %d\n", strlen(s)); // strlen(s): 20
return 0;
}
Should I write
s[i] = '\0';
explicitly after the loop executing to mark the end of the string or it is done automatically? Without s[i] = '\0';
function strlen(s) returns correct value 20.
Yes, you need to add a null terminator yourself. One is not added automatically.
You can verify this by explicitly initializing s
to something that doesn't contain a NUL at byte 20.
char s[MAXLINE] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
If you do that strlen(s)
won't return 20.
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