Search code examples
cnull-character

difference between "\0" and '\0'


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);

Solution

  • 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 an int-sized value representing the character with the encoding value of 0.

    Nits in the code:

    • Don't cast the return value of malloc() in C.
    • Don't scale allocations by sizeof (char), that's always 1 so it adds no value.
    • Pointers are not integers, you should compare against NULL typically.
    • The entire structure of the code makes no sense, there's an allocation in a loop but the pointer is thrown away, leaking lots of memory.