473,692 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 11304
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,(cha r *)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.plwro te:
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,(cha r *)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,"som e 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.plwro te:
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,"som e 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

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

Similar topics

20
8837
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 the 3rd character to V so the string now reads :
6
4755
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 be modified... does that apply on const char*? thanks Sona
13
6135
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 (isalpha(*pt)) printf("A character is found\n");
31
630
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
3
1303
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 = "Randy"; I was under the impression that char* szString should make a pointer variable called szString. So why is the value set to "Randy" when from what I've learned it should be set to &someVariable (the location of some variable). This is...
9
5038
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
605
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
1745
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"); push("add"); works fine however
13
2722
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
9083
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8797
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8800
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5818
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4323
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4557
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2972
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2237
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1957
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.