How can I check if char* variable points to empty string?

CPointersChar

C Problem Overview


How can I check if char* variable points to an empty string?

C Solutions


Solution 1 - C

Check if the first character is '\0'. You should also probably check if your pointer is NULL.

char *c = "";
if ((c != NULL) && (c[0] == '\0')) {
   printf("c is empty\n");
}

You could put both of those checks in a function to make it convenient and easy to reuse.

Edit: In the if statement can be read like this, "If c is not zero and the first character of character array 'c' is not '\0' or zero, then...".

The && simply combines the two conditions. It is basically like saying this:

if (c != NULL) { /* AND (or &&) */
    if (c[0] == '\0') {
        printf("c is empty\n");
    }
}

You may want to get a good C programming book if that is not clear to you. I could recommend a book called "The C Programming Language".

The shortest version equivalent to the above would be:

if (c && !c[0]) {
  printf("c is empty\n");
}

Solution 2 - C

My preferred method:

if (*ptr == 0) // empty string

Probably more common:

if (strlen(ptr) == 0) // empty string

Solution 3 - C

Check the pointer for NULL and then using strlen to see if it returns 0.
NULL check is important because passing NULL pointer to strlen invokes an Undefined Behavior.

Solution 4 - C

An empty string has one single null byte. So test if (s[0] == (char)0)

Solution 5 - C

if (!*ptr) { /* empty string  */}

similarly

if (*ptr)  { /* not empty */ }

Solution 6 - C

I would prefer to use the strlen function as library functions are implemented in the best way.

So, I would write if(strlen(p)==0) //Empty string

Solution 7 - C

Give it a chance:

Try getting string via function gets(string) then check condition as if(string[0] == '\0')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAanView Question on Stackoverflow
Solution 1 - CcodemakerView Answer on Stackoverflow
Solution 2 - CMark RansomView Answer on Stackoverflow
Solution 3 - CAlok SaveView Answer on Stackoverflow
Solution 4 - CBasile StarynkevitchView Answer on Stackoverflow
Solution 5 - CalvinView Answer on Stackoverflow
Solution 6 - CbhuwansahniView Answer on Stackoverflow
Solution 7 - Cikm104View Answer on Stackoverflow