UFC Insider
UFC Insider

Reputation: 838

How to store '\0' in a char array

Is it possible to store the char '\0' inside a char array and then store different characters after? For example

char* tmp = "My\0name\0is\0\0";

I was taught that is actually called a string list in C, but when I tried to print the above (using printf("%s\n", tmp)), it only printed

"My".

Upvotes: 6

Views: 2095

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Yes, it is surely possible, however, furthermore, you cannot use that array as string and get the content stored after the '\0'.

By definition, a string is a char array, terminated by the null character, '\0'. All string related function will stop at the terminating null byte (for example, an argument, containing a '\0' in between the actual contents, passed to format specifier%s in printf()).

Quoting C11, chapter §7.1.1, Definitions of terms

A string is a contiguous sequence of characters terminated by and including the first null character. [...]

However, for byte-by-byte processing, you're good to go as long as you stay within the allocated memory region.

Upvotes: 7

Soren
Soren

Reputation: 14688

The problem you are having is with the function you are using to print tmp. Functions like printf will assume that the string is null terminated, so it will stop when it sees the first \0

If you try the following code you will see more of the value in tmp

int main(int c,char** a){
    char* tmp = "My\0name\0is\0\0";
    write(1,tmp,12);
}

Upvotes: 1

Related Questions