Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a string to null in C

Tags:

c

Is setting a string to '\0' the same thing as setting a string to NULL in other languages? Or... does setting a string to '\0' mean that the string is simply just empty?

char* str = '\0'

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

like image 253
gegardmoussasi Avatar asked Apr 09 '11 21:04

gegardmoussasi


People also ask

Can you set string to null in C?

In practice, NULL is a constant equivalent to 0 , or "\0" . This is why you can set a string to NULL using: char *a_string = '\0'; Download my free C Handbook!

How do you make a string null?

We can do this using the std::string::clear function. It helps to clear the whole string and sets its value to null (empty string) and the size of the string becomes 0 characters. string::clear does not require any parameters, does not return any error, and returns a null value.

How do you empty a string in C?

If you want to zero the entire contents of the string, you can do it this way: memset(buffer,0,strlen(buffer));

What is the use of '\ 0 in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case. The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0 ).


1 Answers

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

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

Note: do not confuse your declaration with the statement in line 3 here

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

which does something entirely different: it sets the first character of the string that str points to to a zero byte, effectively making str point to the empty string.

Terminology nitpick: strings can't be set to NULL; a C string is an array of characters that has a NUL character somewhere. Without a NUL character, it's just an array of characters and must not be passed to functions expecting (pointers to) strings. Pointers, however, are the only objects in C that can be NULL. And don't confuse the NULL macro with the NUL character :-)

like image 134
Jens Avatar answered Sep 21 '22 08:09

Jens