Re: confusion when comparing char * with a string literal
- From: "santosh" <santosh.k83@xxxxxxxxx>
- Date: 17 Mar 2007 11:43:37 -0700
william wrote:
below is a short piece of code I wrote to testify my understanding of
char *, and array.
#include <stdio.h>
Include string.h to get the prototype for strtok.
int main()
{
char *str=NULL;
char x[]="today is good!";
printf("%s", str);
Huh? You're passing a null pointer to printf and telling it to follow
it? I think you meant to initilaise it to point to x.
str = x;
str=strtok(x," ");
strtok need a char * as it's first argument. x is a constant pointer.
if (str=="today") //<==here is line that confuses me
You cannot directly compare strings in C. You'll need to compare them
element by element. The Standard C library function for this is strcmp
or strncmp.
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,
No. The Standard says nothing about the sizes of pointer types. Nor do
you need to assume a particular size for what you're doing. And it's
not a pointer *of* type char. It's a pointer *to* type char.
So, my question is how do we compare arrays and char *(I found that it
is so commonly used as string)?
strcmp/strncmp/memcmp
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?
Yes.
Because I got segfault several times arising from this problem too.
Indeed you'll if you work on pointers that don't point to any valid
object.
.
- Follow-Ups:
- Re: confusion when comparing char * with a string literal
- From: Ben Pfaff
- Re: confusion when comparing char * with a string literal
- References:
- confusion when comparing char * with a string literal
- From: william
- confusion when comparing char * with a string literal
- Prev by Date: ANSI -> K&R ?
- Next by Date: Re: ANSI -> K&R ?
- Previous by thread: Re: confusion when comparing char * with a string literal
- Next by thread: Re: confusion when comparing char * with a string literal
- Index(es):
Relevant Pages
|