473,405 Members | 2,287 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

confusion when comparing char * with a string literal

#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

Mar 17 '07 #1
10 11249
Dnia Sat, 17 Mar 2007 12:01:03 -0700, william napisał(a):
#include <stdio.h>
In C++ it is #include <cstdio>
int main()
{
char *str=NULL;
char x[]="today is good!";
printf("%s", str);
You're trying to print something pointed by a null pointer
[a pointer that points to "nowhere"]. Accessing a null pointer
in C++ is UB. It may crash, it my print "(null)", it may print
some garbage or do nothing.
str=strtok(x," ");
Now you're setting the pointer to the first token found by
strtok. It doesn't point to nowhere until now. It points to
a beginning of "today\0is good!\0"... [the strtok put the
NUL character after first token "today"].
if (str=="today") //<==here is line that confuses me
printf("they equals!\n");
return 0;
}

I printed "str" first, and the console displayed "today".
For me it displays "(null)". And it's true, because the
'str' pointer passed to the first printf is set to nowhere.
However, when I try to comapare 'str' with "today", the
condition failed!
And it's proper behaviour, because you're comparing the
pointers [not strings], and they point to different memory
locations ;) So they're not equal.
Exactly speaking, I know that 'str' is a 4 byte pointer
On some platforms ;)
of char type, so it is not equal to a string.
What string? Do you mean that literal constant?
But even in the gdb, I used 'p str', it printed "today".
And it's also OK, because 'str' points to a memory location,
where "today" lays. But it's not the same "today" as the one
you compare with ;P The first "today" is the part of the
array x, and the second is the literal constant "today" used
in equality expression. That two "today"'s are not the same
memory locations, even if they contain the same sequences
of characters.
So, my question is how do we compare arrays and
char *
strcpy() or strncpy() ;)
(I found that it is so commonly used as string)?
No, it's commonly used to POINT AT character strings/arrays.
one more question: is it true that we have to initialize
a char * or points it to somewhere in memory
Yes. Especially for automatic [local] objects, because they're
not zero-initialized by default and contain garbage [for
pointers: they're aimed at random memory locations].
or to malloc memory to it before we can use it?
Yes, they should point to allocated memory - either by
new/malloc(), or allocated by compiler itself [defined].
Because I got segfault several times arising from
this problem too.
Read some about pointers and string literals.

--
SasQ
Mar 17 '07 #2
hey
you tring to compare constant stinf to char *. first of all you need
to do type casting.
example
String s = "today"
if ( str == (char *)s.c_str())

but i think you cant use "==" with char *. you can use with c++ string
variable.

so u could do like this
if ( strcmp(str,(char *)s.c_str()) == 0)

correct me if i am wrong :)
int main()
{
char *str=NULL;
char x[]="today is good!";
char *s="today";
printf("%s", str);
str=strtok(x," ");
if (strcmp(str,s) == 0) //<==here is line that confuses me
printf("they equals!\n");
getch();
return 0;
}

thanks
sanjay

On Mar 17, 1:23 pm, SasQ <s...@go2.plwrote:
Dnia Sat, 17 Mar 2007 12:01:03 -0700, william napisał(a):
#include <stdio.h>

In C++ it is #include <cstdio>
int main()
{
char *str=NULL;
char x[]="today is good!";
printf("%s", str);

You're trying to print something pointed by a null pointer
[a pointer that points to "nowhere"]. Accessing a null pointer
in C++ is UB. It may crash, it my print "(null)", it may print
some garbage or do nothing.
str=strtok(x," ");

Now you're setting the pointer to the first token found by
strtok. It doesn't point to nowhere until now. It points to
a beginning of "today\0is good!\0"... [the strtok put the
NUL character after first token "today"].
if (str=="today") //<==here is line that confuses me
printf("they equals!\n");
return 0;
}
I printed "str" first, and the console displayed "today".

For me it displays "(null)". And it's true, because the
'str' pointer passed to the first printf is set to nowhere.
However, when I try to comapare 'str' with "today", the
condition failed!

And it's proper behaviour, because you're comparing the
pointers [not strings], and they point to different memory
locations ;) So they're not equal.
Exactly speaking, I know that 'str' is a 4 byte pointer

On some platforms ;)
of char type, so it is not equal to a string.

What string? Do you mean that literal constant?
But even in the gdb, I used 'p str', it printed "today".

And it's also OK, because 'str' points to a memory location,
where "today" lays. But it's not the same "today" as the one
you compare with ;P The first "today" is the part of the
array x, and the second is the literal constant "today" used
in equality expression. That two "today"'s are not the same
memory locations, even if they contain the same sequences
of characters.
So, my question is how do we compare arrays and
char *

strcpy() or strncpy() ;)
(I found that it is so commonly used as string)?

No, it's commonly used to POINT AT character strings/arrays.
one more question: is it true that we have to initialize
a char * or points it to somewhere in memory

Yes. Especially for automatic [local] objects, because they're
not zero-initialized by default and contain garbage [for
pointers: they're aimed at random memory locations].
or to malloc memory to it before we can use it?

Yes, they should point to allocated memory - either by
new/malloc(), or allocated by compiler itself [defined].
Because I got segfault several times arising from
this problem too.

Read some about pointers and string literals.

--
SasQ

Mar 17 '07 #3
Dnia Sat, 17 Mar 2007 21:23:04 +0100, SasQ napisał(a):

Sorry, a little errata:
Now you're setting the pointer to the first token found by
strtok. It doesn't point to nowhere until now.
Should be "from now on" instead of "until now".
[English isn't my native language ;P]
>So, my question is how do we compare arrays and char *

strcpy() or strncpy() ;)
Should be "strcmp() or strncmp()"

--
SasQ
Mar 17 '07 #4
william wrote:
#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".
Your printf in the above program invokes undefined behavior, since it
dereferences a null pointer.
However, when I try to comapare 'str' with "today", the condition failed!
That's to be expected.
Exactly speaking, I know that 'str' is a 4 byte pointer of char type,
The size of a pointer is implementation-defined. Let's simply stick
with "pointer to char".
so it is not equal to a string.
Before the comparison, the string literal gets converted into a pointer to
const char.
But even in the gdb, I used 'p str', it printed "today".
So? You have two pointers pointing to different memory locations. For the
result of that comparison, the content of that memory location (or any of
the following ones) doesn't matter.
So, my question is how do we compare arrays and char *(I found that it
is so commonly used as string)?
It would be better to use std::vector and std::string instead of raw arrays,
pointers and C style strings. Vectors and strings can be compared using ==.
If you must use arrays and C style strings, use std::strcmp() from <cstring>
to compare the strings. For arrays, use std::equal from <algorithm>.
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.
Well, if you use it to read from the address it points to without actually
letting it point to anything, that's not surprising.

Mar 17 '07 #5
SasQ wrote:
Dnia Sat, 17 Mar 2007 21:23:04 +0100, SasQ napisaƂ(a):

Sorry, a little errata:
>Now you're setting the pointer to the first token found by
strtok. It doesn't point to nowhere until now.

Should be "from now on" instead of "until now".
[English isn't my native language ;P]
Depends on how the double negation is to be interpreted. ;-)
Mar 17 '07 #6
Dnia Sat, 17 Mar 2007 13:28:25 -0700, hijkl napisał(a):
you tring to compare constant stinf to char *.
Rather a string literal constant value
["string literal" in short].
first of all you need to do type casting.
It's not the case here.
example:
String s = "today"
Somebody was hungry and has eaten the semicolon :P
if ( str == (char *)s.c_str())
ZOMG o.O
Mixing high-level C++ object code with low-level C-like
code is like mixing a chocolate with a shit :P
And it still won't work, because you're still comparing
two pointers and the equality will be true only if they're
both pointing to the same memory location. If they point
to the different memory locations, the result will be false,
even if they point to the same sequences of characters.
Neither std::string nor casting won't help here :P
but i think you cant use "==" with char *.
He can, but the effects will be different from that he
[and you] suppose ;P
you can use with c++ string variable.
That's the only true sentence you said in this post ;)
so u could do like this
if ( strcmp(str,(char *)s.c_str()) == 0)
OMFG @_@
Why not use just the std::string in all cases?

std::string str1 = "string"; //literal 1 goes to str1
std::string str2 = "string"; //literal 2 goes to str2
if (str1==str2) std::cout << "They're equal";

But remember that equal values not means the same objects.
Look at this carefully:

int x = 2;
int y = 2; //another two, not the same as previous
if (x==y) std::cout << "x and y contains the same values";
if (&x==&y) std::cout << "x and y are the same objects";
else std::cout << "x and y are not the same objects";

BUT... :P
If the use of strtok() is necessary, it might be impossible
to use std::string everywhere, i.e. strtok() returns pointer
to character string, and it's reasonable to use that pointer
for efficiency. Then you must not to compare the string
pointed by that pointer with a string pointed by a pointer
returned from std::string::c_str(). You can simply use
strcmp() with a 'str' pointer and literal constant as a
parameters, like that:

str = strtok(x," ");
if ( strcmp(str,"some string literal") ) {
//they're pointing to strings equal by value
}
correct me if i am wrong :)
So you got what you asked for ;)
PS: Cut citations in your posts.

--
SasQ
Mar 17 '07 #7
william wrote:

I printed "str" first, and the console displayed "today". However,
when I try to comapare 'str' with "today", the condition failed!
Don't multi-post. You posted the question on comp.lang.c (where it was
thoroughly answered).


Brian
Mar 17 '07 #8
On Mar 17, 4:23 pm, SasQ <s...@go2.plwrote:
Dnia Sat, 17 Mar 2007 12:01:03 -0700, william napisał(a):
#include <stdio.h>

In C++ it is #include <cstdio>
int main()
{
char *str=NULL;
char x[]="today is good!";
printf("%s", str);

You're trying to print something pointed by a null pointer
[a pointer that points to "nowhere"]. Accessing a null pointer
in C++ is UB. It may crash, it my print "(null)", it may print
some garbage or do nothing.
str=strtok(x," ");

Now you're setting the pointer to the first token found by
strtok. It doesn't point to nowhere until now. It points to
a beginning of "today\0is good!\0"... [the strtok put the
NUL character after first token "today"].
if (str=="today") //<==here is line that confuses me
printf("they equals!\n");
return 0;
}
I printed "str" first, and the console displayed "today".

For me it displays "(null)". And it's true, because the
'str' pointer passed to the first printf is set to nowhere.
However, when I try to comapare 'str' with "today", the
condition failed!

And it's proper behaviour, because you're comparing the
pointers [not strings], and they point to different memory
locations ;) So they're not equal.
Exactly speaking, I know that 'str' is a 4 byte pointer

On some platforms ;)
of char type, so it is not equal to a string.

What string? Do you mean that literal constant?
But even in the gdb, I used 'p str', it printed "today".

And it's also OK, because 'str' points to a memory location,
where "today" lays. But it's not the same "today" as the one
you compare with ;P The first "today" is the part of the
array x, and the second is the literal constant "today" used
in equality expression. That two "today"'s are not the same
memory locations, even if they contain the same sequences
of characters.
So, my question is how do we compare arrays and
char *

strcpy() or strncpy() ;)
(I found that it is so commonly used as string)?

No, it's commonly used to POINT AT character strings/arrays.
one more question: is it true that we have to initialize
a char * or points it to somewhere in memory

Yes. Especially for automatic [local] objects, because they're
not zero-initialized by default and contain garbage [for
pointers: they're aimed at random memory locations].
or to malloc memory to it before we can use it?

Yes, they should point to allocated memory - either by
new/malloc(), or allocated by compiler itself [defined].
Because I got segfault several times arising from
this problem too.

Read some about pointers and string literals.

--
SasQ
Thank you very much, SasQ

Mar 19 '07 #9
str = strtok(x," ");
if ( strcmp(str,"some string literal") ) {
//they're pointing to strings equal by value
}
Yes, this worked totally well.
correct me if i am wrong :)

So you got what you asked for ;)

PS: Cut citations in your posts.

--
SasQ

Mar 19 '07 #10
On 17 Mar, 20:23, SasQ <s...@go2.plwrote:
Dnia Sat, 17 Mar 2007 12:01:03 -0700, william napisał(a):
#include <stdio.h>

In C++ it is #include <cstdio>
You only made half the correction. If you change <stdio.hto <cstdio>
then you need to change printf to std::printf. And unless you're going
to be inconsistent, you'll want to include <cstringrather than
<string.hso strcmp and friends will also be in the std namespace.

Or you could decide that since most compilers implement <cxxxheaders
incorrectly, putting names in both the std and the global namespace
(so use of printf rather than std::printf often works after including
<cstdio>), then the choice _in practice_ is between technically
deprecated code compiling successfully and technically incorrect code
compiling successfully, in which case the <cxxxheaders aren't worth
bothering with. That's my approach. YMMV.

Gavin Deane

Mar 19 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
by: dms | last post by:
Hi all, If you have a char pointer (char *var), is there a way I can manipulate specific characters or blocks of characters within the string? eg: char *name; name = "David" then change...
6
by: Sona | last post by:
Hi, What's the advantage/disadvantage of using a "const char*" over a "char*" ? I read some place that char* are string literals that on some machines are stored in a read only memory and cannot...
13
by: Nicholas | last post by:
How can I compare char* with integers and characters contained in the str, where integers can be one digit or more? void Access(char *str) { char *pt = str; while (pt != '0') { if...
31
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
3
by: quadraticformula | last post by:
I recently purchased Stephen Davis's book C++ For Dummies, and came across a simple declaration that I don't understand the workings of. About 1/5 way through the book I see char* szString =...
9
by: subramanian100in | last post by:
Suppose we have char *a = "test message" ; Consider the comparison if (a == "string") ..... Here "string" is an array of characters. So shouldn't the compiler
18
by: william | last post by:
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);
8
by: merrittr | last post by:
I have been having troubles getting "string" input pushed on to the stack in the assn1. The funny thing is I can push a literal on no problem so push("push i 0"); push("push i 1");...
13
by: Andreas Eibach | last post by:
Hi, let's say I have this: #include <string.h> #define BLAH "foo" Later on, I do this:
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.