What kind! (char *) means in C

I looked at an example and I saw this:

char *str; /* ... */ if (!str || !*str) { return str; } 

Does this mean it's empty or something?

+6
source share
4 answers

str is a char pointer. ! denies that. Basically !str will evaluate to true (1) when str == NULL .

The second part says: (if str points to something), evaluate to true (1), if the first character is zero char ( '\0' ) - this means that it is an empty string.

Note:
*str parses the pointer and extracts the first character. This is the same as str[0] .

+6
source

!str means there is no memory for str . !*str means that str points to an empty string.

+4
source

Before asking, you can do small tests.

 #include <stdio.h> int main() { char *str = "test"; printf("%d\n",*str); printf("%c\n",*str); // str[0] printf("%d\n",str); if (!str || !*str) { printf("%s",str); } return 0; } 

Value ! - denial. With the exception of 0 each value is true for the if condition. Here str and *str return values ​​that are not 0 . So you can conclude.

+2
source

The first expression !str evaluates to true if str is set to NULL , and false if anything else is set, regardless of whether the allocated memory is allocated or not. This can lead to undefined behavior if str remains set to memory that is no longer active.

The second expression !*str evaluates to true if the value at str in the address is \0 (a null character), but it does not evaluate at all if !str evaluates to true because of the action of the short circuit operator boolean OR.

0
source

All Articles