473,939 Members | 16,067 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,"hel lo")

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(strcp y 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 2890
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**********@hy dbad.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(strcp y 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.stanfor d.edu> wrote in message news:<87******* *****@pfaff.sta nford.edu>...
vi**********@hy dbad.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(strcp y 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,"hel lo")

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(strcp y 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
5160
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 starting at position 0. I thought that char was 2 bytes, but this makes it seem as though it is just 1 when I write to a file. Why is this? I imagine the extra bit is just a null bit (correct me if I'm wrong). I don't know if this helps but when I...
7
10640
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 namespace std; : : vector<string>* getTyphoon()
7
3191
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 libraries. Here's my situation. My system is Red Hat Linux 9, using the Borland C++BuilderX Personal IDE (which uses the g++ compiler).
11
3377
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
5735
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. ================================================================= Error 19: "CORBAManagerMessages.h", line 4 # Unexpected 'std'. using std::string; ^^^
6
17223
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, process and output to the screen in my application when a message arrived. But the problem is how do I read the SMS message immediately when it arrived without my handphone BeEPINg for new message ? I read up the AT commands, but when getting down...
13
6269
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 get me, which brings me to... I'm trying to create a program that gets a string from standard input and then manipulates it a little bit. It has to be a char array and not use string from the library. Here are my prototypes:
11
2728
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 receiving a char buffer into a string? Reason I ask is otherwise I have to guess at what size buffer to create? And then copy buffer to a string. Doesn't seem ideal.
9
1802
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
5107
by: Amera | last post by:
hello , I have written these codes : Mydll file : Mydll.h #ifndef MYDLL_H
0
10134
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9963
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
11293
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
10659
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...
1
8218
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7389
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
6077
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
6297
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3502
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.