When I read BlueZ source code, I often see char
arrays defined like this:
// bluez/android/sco-msg.h static const char BLUEZ_SCO_SK_PATH[] = "\0bluez_sco_socket";
What good is it to define the first element as \0
?
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.
You need the null character to mark the end of the string. C does not store any internal information about the length of the character array or the length of a string, and so the null character/byte \0 marks where it ends.
A C-style string is a null (denoted by \0 ) terminated char array. The null occurs after the last character of the string. For an initialization using double quotes, "...", the compiler will insert the null .
Use the strlen Function to Find Length of Char Array In some scenarios, char arrays that were initialized or stored as the null-terminated character strings can be measured for size using the strlen function, which is part of the C standard library string utilities.
In your particular case this array is used as pathname for a PF_LOCAL
socket; see here. And leading NUL is used to point that address is an abstract one. From man 7 unix:
an abstract socket address is distinguished by the fact that sun_path[0] is a null byte ('\0').
And this is the only reason why the first element is \0
.
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