The difference between "\ 0" and "\ 0"

I am trying to understand the following code snippet, but I am confused between "\ 0" and "\ 0". I know him stupid, but kindly help me

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

Thanks in advance

+7
c null-character
source share
3 answers

Double quotation marks create string literals. Thus, "\0" is a string literal containing the single character '\0' , and the second as a terminator. This is a dumb way to write an empty string ( "" is an idiomatic way).

Single quotes are for character literals, so '\0' is an int dimensional value representing a character with a code value of 0.

Nits in code:

  • Do not enter the return value of malloc() in C.
  • Do not scale the distribution of sizeof (char) , which is always 1, so it does not add a value.
  • Pointers are not integers, you should compare with NULL as a rule.
  • The whole structure of the code does not make sense, there is a selection in the loop, but the pointer is thrown out, skipping a lot of memory.
+8
source share

They are different.

"\0" is a string literal that has two consecutive 0s and is roughly equivalent:

 const char a[2] = { '\0', '\0' }; 

'\0' is an int with a value of 0. You can always use 0, where you need to use '\0' .

+10
source share

\0 is the null terminator character.

"\0" matches {'\0', '\0'} . This is a string written by an intricate programmer who does not understand that string literals always have zero termination automatically. Correctly written code would be "" .

The if (str_temp=='\0') line if (str_temp=='\0') is stupid, it should be if (str_temp==NULL) . Now that this happens, \0 equivalent to 0, which is the constant of the null pointer, so the code works out of luck.

Taking a strlen string, where \0 is the first character, is not very significant. You will get zero string length.

+6
source share

All Articles