I am trying to understand following piece of code, but I am confused between "\0"
and '\0'
.I know its silly but kindly help me out
#define MAX_HISTORY 20
char *pStr = "\0";
for(x=0;x<MAX_HISTORY;x++){
str_temp = (char *)malloc((strlen(pStr)+1)*sizeof(char));
if (str_temp=='\0'){
return 1;
}
memset(str_temp, '\0', strlen(pStr) );
strcpy(str_temp, pStr);
Double quotes create string literals. So
"\0"
is a string literal holding the single character'\0'
, plus a second one as the terminator. It's a silly way to write an empty string (""
is the idiomatic way).Single quotes are for character literals, so
'\0'
is anint
-sized value representing the character with the encoding value of 0.Nits in the code:
malloc()
in C.sizeof (char)
, that's always 1 so it adds no value.NULL
typically.They are different.
"\0"
is a string literal which has two consecutive 0's and is roughly equivalent to:'\0'
is anint
with value 0. You can always 0 wherever you need to use'\0'
.\0
is the null terminator character."\0"
is the same as{'\0', '\0'}
. It is a string written by a confused programmer who doesn't understand that string literals are always null terminated automatically. Correctly written code would have been""
.The line
if (str_temp=='\0')
is nonsense, it should have beenif (str_temp==NULL)
. Now as it happens,\0
is equivalent to 0, which is a null pointer constant, so the code works, by luck.Taking
strlen
of a string where\0
is the first character isn't very meaningful. You will get string length zero.