Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why define \0 as the first element of a char array in C?

Tags:

arrays

c

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?

like image 206
user1923105 Avatar asked Jul 11 '16 10:07

user1923105


People also ask

Why a char array must end with a null character?

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.

Why do we need to use null characters to denote the end of a string in C?

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.

Are char arrays null-terminated C?

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 .

How do I find the end of a char array?

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.


1 Answers

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.

like image 167
Sergio Avatar answered Sep 24 '22 03:09

Sergio