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

Character array without a null terminator in C

Sometimes I am using sequences of characters (strings) except the null terminator is not needed or wanted, for example if I am using memcpy() and the length is already known. A such, I prefer to omit the null terminator. A cumbersome way to do this would be declaring an array:

char no_term[5] = {'h', 'e', 'l', 'l', 'o'};

However, I would prefer to use quoted strings, as these are much more efficient to program with. However quoted strings automatically include a null terminator at the end. But would specifying the array size to exclude the null terminator invoke undefined behavior? Is the following valid C, as long as I do not use these where a null terminated string is required (e.g., passing them to strlen())?

char no_term[5] = "hello";
char no_term_array[3][3] = {"foo", "bar", "baz"};

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 :

According to §6.7.9 ¶14 of the ISO C11 standard, arrays of character type may be initialized from a string literal, even if there is no room for the terminating null character.

So yes, your posted code is valid and will not invoke undefined behavior.

Note however that this is only legal in C, not C++.

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