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");
}
Answer from codemaker on Stack OverflowCheck 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");
}
My preferred method:
if (*ptr == 0) // empty string
Probably more common:
if (strlen(ptr) == 0) // empty string
Empty value detection for char* type variable
c++ - how to check const char* values one by one - Stack Overflow
Check if something wrote into char array - C++ Forum
How to know a char* is an array? - C++ Forum
You didn't initialize test. If you want it to be NULL initially, you have to set it:
const char* test = NULL;
C and C++ do not initialize pointers to NULL automatically. If you do not assign it a value, it still has a value, it is just an unknown, indeterminate value. It could be NULL, it could be something else.
In your sample code, test has a value, but it is unknown.
So your if-statement might or might not be true.
When I try using .isEmpty() or isspace() it gives me the message that "expression must have class type" and str != "" doesn't seem to work. The type I'm using is "const char *".
I know that some compilers give error on following:
char* test2;test2 = "";
Is it valid or equivalent, to do the following?
char* test2;test2[0] = '\0';
Thank in advance for your response.