473,387 Members | 1,495 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,387 software developers and data experts.

Using == with char *

Hi !

I have been experimenting with char * for a while now. I have two pieces of
code :

Code1 :
=====

char *ptr = "hello";

if (ptr == "hello")
{
printf("true\n");
}
else
{
printf ("false\n");
}

Code2:
=====

char *ptr = (char *) malloc(6* sizeof(char));
strcpy(ptr,"hello")

if (ptr == "hello")
{
printf("true\n");
}
else
{
printf ("false\n");
}
Code1 prints true while Code2 prints false.

Now, I know that Code1 is a pathetic way of programming and it
will result in a segmentation fault in some memory operation(strcpy etc).

But I have 2 questions regarding this.

1. Why are the the answers different in Code1 and Code2. I had expected
the answers in both the cases to be false.

2. What is the difference between == operator and stcmp ?.
Why doesn't == work for strings (ASCII and binary comparison ????)

Thanks !

Regards,
Vishal
Nov 13 '05 #1
3 2858
Vishal Ladha wrote:
....
char *ptr = "hello";

if (ptr == "hello") .... 2. What is the difference between == operator and stcmp ?.
Why doesn't == work for strings (ASCII and binary comparison ????)


http://www.eskimo.com/~scs/C-faq/q8.2.html

Jirka

Nov 13 '05 #2
vi**********@hydbad.tcs.co.in (Vishal Ladha) writes:
Code1 :
=====

char *ptr = "hello";

if (ptr == "hello")
{
printf("true\n");
}
else
{
printf ("false\n");
} [...] Now, I know that Code1 is a pathetic way of programming and it
will result in a segmentation fault in some memory operation(strcpy etc).


It's not useful, but there's nothing wrong with it from a
standards perspective. It certainly doesn't invoke undefined
behavior.

Maybe you mean that if you try to strcpy() over ptr as assigned
above, you'll get undefined behavior. That's true. But it's
really quite unclear to me what you actually mean.
--
"This is a wonderful answer.
It's off-topic, it's incorrect, and it doesn't answer the question."
--Richard Heathfield
Nov 13 '05 #3
Ben Pfaff <bl*@cs.stanford.edu> wrote in message news:<87************@pfaff.stanford.edu>...
vi**********@hydbad.tcs.co.in (Vishal Ladha) writes:
Code1 :
=====

char *ptr = "hello";

if (ptr == "hello")
{
printf("true\n");
}
else
{
printf ("false\n");
} [...]
Now, I know that Code1 is a pathetic way of programming and it
will result in a segmentation fault in some memory operation(strcpy etc).


It's not useful, but there's nothing wrong with it from a
standards perspective. It certainly doesn't invoke undefined
behavior.

Maybe you mean that if you try to strcpy() over ptr as assigned
above, you'll get undefined behavior. That's true. But it's
really quite unclear to me what you actually mean.


I think I have got the answer from Darrell Grainger. Here it is

================================================== ==============

Hi !
I have been experimenting with char * for a while now. I have two pieces of
code :

Code1 :
=====

char *ptr = "hello";

This line of code creates two things. The first thing is a variable ptr.
The second thing is the string literal "hello". It then assigned the
address of the string literal to the variable ptr. For example, if the
compiler puts the string literal "hello" in memory location 5000 then ptr
equals 5000.

if (ptr == "hello")

The compiler could create a second string literal "hello" but a good
compiler will know that a constant string literal "hello" already exists
and it will use that same string for this comparison. This means that the
string literal here *CAN* be the same memory location as the one above.

In the case of your compiler, they are the same string. Therefore, the
comparison will be true. It is equally possible for the comparison to be
false. For example, the above assignment makes "hello" a constant string
literal. Change it to:

char ptr[] = "hello";

and you *MIGHT* find this if statement is false.

{
printf("true\n");
}
else
{
printf ("false\n");
}

Code2:
=====

char *ptr = (char *) malloc(6* sizeof(char));
strcpy(ptr,"hello")

In this case, ptr is being assigned the address of a writable memory
location. The string literal "hello" *MIGHT* be read only. In all cases,
the memory location of the malloc memory and the memory location of the
string literal "hello" will be different.

if (ptr == "hello")

Since ptr holds the address of the malloc memory and that is a different
memory location then the string literal "hello", this will be false.

{
printf("true\n");
}
else
{
printf ("false\n");
}
Code1 prints true while Code2 prints false.

Yes. Code1 can print true or false depending on the compiler. Code2 will
always print false.

Now, I know that Code1 is a pathetic way of programming and it
will result in a segmentation fault in some memory operation(strcpy etc).

It depends on the compiler. If your compiler places string literals, like
"hello", in read only memory locations then attempting to alter it, via
ptr, will result in a segmentation fault. If your compiler places string
literals in writable memory then it will not cause a segmenttation fault.

But I have 2 questions regarding this.

1. Why are the the answers different in Code1 and Code2. I had expected
the answers in both the cases to be false.

See above.

2. What is the difference between == operator and stcmp ?.
Why doesn't == work for strings (ASCII and binary comparison ????)

A string is a concept. There is actually no atomic data type called a
string in C language. A string is REALLY an array of char with a '\0'
character marking the end of the useful array. The == operator cannot be
used to compare arrays. When you pass the name of an array to a function
the receiving function actually receives the address of the first element.
To be consistent, the == operator works the same way. Thus if I have:

char s1[] = "hello";
char s2[] = "hello";

if(s1 == s2)
puts("Will never get here.");
else
puts("This will always print");

It is the same as:

char s1[] = "hello";
char s2[] = "hello";

if(&s1[0] == &s2[0])
puts("Will never get here.");
else
puts("This will always print");

The address of the start of s1 will not be the same as the address of s2.
The contents are the same but the memory locations are different.

================================================== =====================
Nov 13 '05 #4

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

Similar topics

3
by: Mark Miller | last post by:
I have a char array and when I write it to a file using BinaryWriter the position of the pointer is the size of the array + 1. For example: writing char leaves the pointer at position 26 after...
7
by: Forecast | last post by:
I run the following code in UNIX compiled by g++ 3.3.2 successfully. : // proj2.cc: returns a dynamic vector and prints out at main~~ : // : #include <iostream> : #include <vector> : : using...
7
by: sbobrows | last post by:
{Whilst I think much of this is OT for this newsgroup, I think the issue of understanding diagnostics just about gets under the door. -mod} Hi, I'm a C++ newbie trying to use the Boost regex...
11
by: TheDD | last post by:
Hello, i don't manage to use the tolower() function: #include <algorithm> #include <iostream> #include <locale> #include <string> using std::cout;
5
by: Enos Meroka | last post by:
Hallo, I am a student doing my project in the university.. I have been trying to compile the program using HP -UX aCC compiler, however I keep on getting the following errors. ...
6
by: ransoma22 | last post by:
I developing an application that receive SMS from a connected GSM handphone, e.g Siemens M55, Nokia 6230,etc through the data cable. The application(VB.NET) will receive the SMS automatically,...
13
by: Superman859 | last post by:
Hello everyone. Heads up - c++ syntax is killing me. I do quite well in creating a Java program with very few syntax errors, but I get them all over the place in c++. The smallest little things...
11
by: Angus | last post by:
I am working with a C API which often requires a char* or char buffer. If a C function returns a char* I can't use string? Or can I? I realise I can pass a char* using c_str() but what about...
9
by: chikkubhai | last post by:
Why is the result different for the following set of two code snippets Code without using this pointer #include <string> #include <iostream> using namespace std; struct X { private:
4
by: Amera | last post by:
hello , I have written these codes : Mydll file : Mydll.h #ifndef MYDLL_H
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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...

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.