Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store '\0' in a char array

Tags:

c

string

printf

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".

like image 602
UFC Insider Avatar asked Jan 08 '17 17:01

UFC Insider


People also ask

How do you store zeros in a char?

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() ).

How do you store values in a char array?

To store the words, a 2-D char array is required. In this 2-D array, each row will contain a word each. Hence the rows will denote the index number of the words and the column number will denote the particular character in that word.

What is the purpose of '\ 0 character in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case. The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0 ).

Does a char array start with \0?

The null-character \0 is put at the end of the array to mark the end of the array.


2 Answers

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.

like image 191
Sourav Ghosh Avatar answered Oct 08 '22 23:10

Sourav Ghosh


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);
}
like image 24
Soren Avatar answered Oct 09 '22 00:10

Soren