I am writing a driver for an embedded system that runs a custom version of modified linux (Its a handscanner). The manufacturer supplys a custom Eclipse Juno distribution with a few libraries and examples inbound.
The output I receive from the comport comes in form of a standard character array. I am using the individual characters in the array to convey information (error ids and error codes) like this:
if (tmp[i] == 250])
Where tmp
is a character array in form of char tmp[500];
that is first initialized to 0
and then filled with input from the comport.
My question is:
Assuming I iterate through every piece of the array, is it safe to use 0
(as in \0
) at any point before the end of the Array? Assuming I am:
int
array)The reason im asking is because I had several coworkers tell me that I should never ever ever use a character array that contains \0
before the end, no matter the circumstances.
My code doing this currently performs as expected, but im unsure if it might cause problems later.
Rewriting it to avoid this behaviour would be a non-trivial chunk of work.
If your char array represents a string then if you omit the null terminator every function working with C strings will not return the correct value or will behave differently than expected.
The \0 character marks the end of the string stored in a char array, if (and only if) that char array is intended to store a string. A char array is just a char array. It stores independent integer values ( char is just a small integer type).
// Pre: char array must have null character at the end of data. Thus, we first find out how long the data is. The variable length will be the index of the first null character in the array, which is also the length of the data.
C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.
Using an array of char
as an array of small integers is perfectly fine. Just be careful not to pass it to any kind of function that expects "strings".
And if you want to be more explicit about it, and also make sure that the array is using unsigned char
you could use uint8_t
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With