For example in this code:
char *ptr = "string";
Is there a null terminator in the stored in the ptr[6]
address?
When I test this and print a string, it prints "string", and if I print the ptr[6]
char I get ''. I wanted to test this further so I did some research and found someone saying that strlen will always crash if there is not a null terminator. I ran this in my code and it returned 6, so does this mean that assigning a string to a char pointer initializes with a null terminator or am I misunderstanding what's happening?
CodePudding user response:
Yes. String literals used as pointers will always end in a NUL
byte. String literals used as array initializers will too, unless you specify a length that's too small for it to (e.g., char arr[] = "string";
and char arr[7] = "string";
both will, but char arr[6] = "string";
won't).