#2 is a little confusing (I think) and a little inaccurate.
Quote:
2. if(str[0] !='\0') is used to check whether the first element of the array is NULL or not. '\0' and NULL are the same.
'\0' == (char) 0.
NULL means a pointer to nothing.
(anytype *) 0 gets coverted to NULL by the compiler.
anyway checking if a char == NULL does not make any sense although it may compile in VC it won't on some platforms (esp Solaris, I think) or at least they complain.
short answer: do this
if(str!=NULL && str[0] !='\0') just as rajeev said.
Also give the points to him I think he explained it well except for this subtle point.
rajeev_devin
Reply to frogger1999:
The character '\0' is internally represented as 0, and the macro NULL also has the value 0. You can check it out. I am not speaking in terms of compiler. In different compilers we may have to type cast the thing also.
Hope this may clarify the thing further...
pigyc
ASKER
am i getting it right?explain a bit of stack, please.
so if i define something in a local function like this:
char str[256];
....
then i am allocating memory in statck? so i just need to check
if(str[0] !='\0')
strcpy(str, someRealNonEmtyString) ??
if I do malloc for str and put data record by record into array of str, then use
if(!str && str[0] !='\0') ??
i am assuming if have something like this,
char str2[256];
char str="hello";
char *ptr = str,
then would it be enough to check this ptr is not null(if(!ptr), or do i need to put
if(!ptr && ptr[0]!='\0')
strcpy(str2, ptr)
if(item->name != NULL && item->name[0]!='\0')
/*do i need to use both of above to make sure name is empty??*/
do somehting.....
}
}
gj62
Empty is different than NULL -
A string is empty if string[0]==0; or string[0]=='\0';, whichever you prefer.
If string==NULL, then string is uninitialized - the pointer is not valid.
If string is NULL, then the statement string[0]==0, or any other reference, will cause an exception...
So if it might be set to NULL, you need to test for it.
Lastly, realize that you've allocated no space to the strings in your struct - you will need to do that with malloc, or by setting the pointer equal to an existing string, etc...
Quote:
2. if(str[0] !='\0') is used to check whether the first element of the array is NULL or not. '\0' and NULL are the same.
'\0' == (char) 0.
NULL means a pointer to nothing.
(anytype *) 0 gets coverted to NULL by the compiler.
anyway checking if a char == NULL does not make any sense although it may compile in VC it won't on some platforms (esp Solaris, I think) or at least they complain.
short answer: do this
if(str!=NULL && str[0] !='\0') just as rajeev said.
Also give the points to him I think he explained it well except for this subtle point.