How to check whether a char pointer is an empty string?
-
Hey I have a variable, char * p which could sometimes have a string or sometimes it will be empty. How to check whether "p" has a string in it or not? I see that its not possible to do something like, if(p != "") { } Thanks
Perhaps you could use
if(*p = 0);
But then this assumes you initialize the pointer when it is emptied.
char* p = NULL;
// use your pointer
p = &some_char_array;
// do whatever with it
p = NULL;Hope that helps.
Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193
-
Perhaps you could use
if(*p = 0);
But then this assumes you initialize the pointer when it is emptied.
char* p = NULL;
// use your pointer
p = &some_char_array;
// do whatever with it
p = NULL;Hope that helps.
Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193
-
Hey I have a variable, char * p which could sometimes have a string or sometimes it will be empty. How to check whether "p" has a string in it or not? I see that its not possible to do something like, if(p != "") { } Thanks
you may check for an empty string with
if (strlen(p)==0)
{
//..
}the above check, of course, assumes
p
pointing to a valid string (empty string is a valid one). i.e. such code doesn't check ifp
is a valid pointer, to spot the difference, try:char *p, *q;
p="";
q=NULL;printf("strlen(p)=%d\n", strlen(p));
printf("strlen(q)=%d\n", strlen(q));If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
[My articles] -
Perhaps you could use
if(*p = 0);
But then this assumes you initialize the pointer when it is emptied.
char* p = NULL;
// use your pointer
p = &some_char_array;
// do whatever with it
p = NULL;Hope that helps.
Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193
-
Hey I have a variable, char * p which could sometimes have a string or sometimes it will be empty. How to check whether "p" has a string in it or not? I see that its not possible to do something like, if(p != "") { } Thanks
Why not use a string type? There you can check easily. However, if you have to use a char *, then you have to care about setting the pointer to NULL or to a '\0' char. this would be the end of a string. As you like. The cleaner version, I would say, would be to use a string object. Cheers
You have the thought that modern physics just relay on assumptions, that somehow depends on a smile of a cat, which isn’t there.( Albert Einstein)