Setting a string with a null value in C

Sets a string to '\ 0' the same as setting a string to NULL in other languages? Or ... setting a string to '\ 0' means the string is just empty?

char* str = '\0' 

I have different functions to use for empty strings and empty strings, so I don't want to accidentally call one of my empty string functions a null string.

+4
source share
2 answers

Your string char *str = '\0'; actually sets str to (equivalent) NULL. This is because '\0' in C is an integer with the value 0, which is a valid null pointer constant. It is extremely confusing, though :-)

Creating str (pointer to) an empty string is done using str = ""; (or using str = "\0"; ), which will make str a point in an array of two zero bytes).

Note. Do not confuse your declaration with the instruction on line 3 here

 char *str; /* ... allocate storage for str here ... */ *str = '\0'; /* Same as *str = 0; */ 

which does something completely different: it sets the first character of the string, which str points to a null byte, effectively making str point to an empty string.

Nitpick terminology: strings cannot be set to NULL; string C is an array of characters, somewhere a NUL character. Without a NUL character, it is just an array of characters and should not be passed to functions that expect strings (pointers). Pointers, however, are the only objects in C that can be NULL. And do not confuse the NULL macro with the NUL character :-)

+15
source

No, in this case you are pointing to a real (non-null) string with a length of 0. You can simply do the following to set it to a valid null:

 char* str = NULL; 
+1
source

Source: https://habr.com/ru/post/1347390/


All Articles