W
william
below is a short piece of code I wrote to testify my understanding of
char *, and array.
#include <stdio.h>
int main()
{
char *str=NULL;
char x[]="today is good!";
printf("%s", str);
str=strtok(x," ");
if (str=="today") //<==here is line that confuses me
printf("they equals!\n");
return 0;
}
I printed "str" first, and the console displayed "today". However,
when I try to comapare 'str' with "today", the condition failed!
Exactly speaking, I know that 'str' is a 4 byte pointer of char type,
so it is not equal to a string. But even in the gdb, I used 'p str',
it printed "today".
So, my question is how do we compare arrays and char *(I found that it
is so commonly used as string)?
one more question: is it true that we have to initialize a char * or
points it to somewhere in memory, or to malloc memory to it before we
can use it?
Because I got segfault several times arising from this problem too.
Thank you for your reply in advance!
Ji
char *, and array.
#include <stdio.h>
int main()
{
char *str=NULL;
char x[]="today is good!";
printf("%s", str);
str=strtok(x," ");
if (str=="today") //<==here is line that confuses me
printf("they equals!\n");
return 0;
}
I printed "str" first, and the console displayed "today". However,
when I try to comapare 'str' with "today", the condition failed!
Exactly speaking, I know that 'str' is a 4 byte pointer of char type,
so it is not equal to a string. But even in the gdb, I used 'p str',
it printed "today".
So, my question is how do we compare arrays and char *(I found that it
is so commonly used as string)?
one more question: is it true that we have to initialize a char * or
points it to somewhere in memory, or to malloc memory to it before we
can use it?
Because I got segfault several times arising from this problem too.
Thank you for your reply in advance!
Ji