Zero-terminated string compiler option for gcc

Update

it turns out that this is just another example: "C ++ not c blues"


What I want

const char hex[16] = "0123456789ABCDEF"; 

the only thing that works

 char hex[16] = "0123456789ABCDE"; hex[15] = "F"; 

Are there any compiler options or something that I can do so that non-null strings are completed in the gcc compiler. so that I can create a (n) persistent array

+7
c ++ c gcc string null-terminated
source share
5 answers

There is no need for a compiler; it is no longer completed by NUL. The standard states that NUL should be added only if it can fit, otherwise it will be an overflow. Maybe the next byte in the memory of your array is \0

& section; 6.7.8p14

An array of character types can be initialized with a string literal character, optionally enclosed in curly braces. Sequential characters of a character string are literal ( including the termination of a null character if there is space , or if the array has an unknown size) to initialize the elements of the array.

+11
source share

Not. NUL-terminated strings are an integral part of the language. You can have an array of characters, although you can specify each character one at a time:

 char hex [] = {'0', '1', '2', ... 'F'}; 
+7
source share

You answered your question. If you explicitly give the array a length, as in:

 const char hex[16] = "0123456789ABCDEF"; 

then of course it will not be completed from zero because there is no storage reserved for zero completion. ( hex[16] is outside of the object and thus reading or writing is undefined behavior. If this happens as 0, then UB for ya ...)

This is only if you leave the length implicit, as in:

 const char hex[] = "0123456789ABCDEF"; 

or if you use a string literal as an object, and not as an initializer, then it will have zero completion.

By the way, why do you care if there is zero termination or not if you do not plan to use it. Are you trying to shave bytes from your binary ?:-)

+5
source share

Strings have zero completion in C. If you want to fill a char array with zero completion, you can use an array initializer.

0
source share

I find the question a bit unclear: in C, Qoted initialization:

 static const char hex[16] = "0123456789ABCDEF"; 

is legal. In C ++, this is not the case. So this is one piece of code that won't work (fortunately, at compile time) when you switch from C to C ++.

It would be nice to be able to force format string literals without completing \ 0 bytes. Something like:

 static const char hex[16] = "0123456789ABCDEF\!0"; 

where \!0 at the end tells the compiler not to reset the line zero! \! or even \!0 somewhere else in the line will behave unmodified, so just pull out the literal ! or !0 .

0
source share

All Articles