When is it necessary to explicitly provide space for a NULL
character in C strings.
For eg;
This works without any error although I haven't declared str
to be 7 characters long,i.e for the characters of string plus NULL
character.
#include<stdio.h>
int main(){
char str[6] = "string";
printf("%s", str);
return 0;
}
Though in this question https://stackoverflow.com/a/7652089 the user says
"This is useful if you need to modify the string later on, but know that it will not exceed 40 characters (or 39 characters followed by a null terminator, depending on context)."
What does it mean by "depending on context" ?
When is it necessary to explicitly provide space for a NULL character in C strings?
Always. Not having that \0
character there will make functions like strcpy
, strlen
and printing via %s
behave wrong. It might work for some examples (like your own) but I won't bet anything on that.
On the other hand, if your string is binary and you know the length of the packet you don't need that extra space. But then you cannot use str*
functions. And this is not the case of your question, anyway.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments