Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading