Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-terminate string: Use '\0' or just 0?

If I need to null-terminate a String, should I rather use \0 or is a simple 0 also enough?

Is there any difference between using

char a[5];
a[0] = 0;

and

char a[5];
a[0] = '\0';

Or is \0 just preferred to make it clear that I'm null-terminating here, but for the compiler it is the same?

like image 871
erg Avatar asked Mar 02 '16 12:03

erg


People also ask

Is 0 the null terminator?

In programming languages/context, a null character is represented by the escape sequence \0, and it marks the end of a character string.

How do you null terminate a string?

The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.

Why do we need terminating null (\ 0 character in a string?

A "string" is really just an array of char s; a null-terminated string is one where a null character '\0' marks the end of the string (not necessarily the end of the array). All strings in code (delimited by double quotes "" ) are automatically null-terminated by the compiler.

Does '\ 0 take up memory?

\0 is just one more character from malloc and free perspective, they don't care what data you put in the memory.


1 Answers

'\0' is an escape sequence for an octal literal with the value of 0. So there is no difference between them

Side note: if you are dealing with strings than you should use a std::string.

like image 197
NathanOliver Avatar answered Sep 27 '22 20:09

NathanOliver