简体   繁体   中英

Does directly assigning a string of char's to a char pointer on initialization automatically add a null terminator?

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?

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 (eg, char arr[] = "string"; and char arr[7] = "string"; both will, but char arr[6] = "string"; won't).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM