473,883 Members | 1,769 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

the difference between "const char* s" and "char* const s"

Hi all! I've taken some time on learning the difference between
"pointers to const variables" and "const pointer variables". The
question is: in the following code, can we change the contents of the
const pointer (i.e. t)? I got a segmentation fault in the last for
loop. Thanks in advance!

#include <iostream>

using namespace std;

main ()
{
const char* s; // pointer to const variable
s = "hello";
for (; *s; s++)
// *s = 'a'; WRONG! the string is const, so it cannot be
changed
cout << *s << endl;
s = "world"; // OK! reassign s to another string. the pointer is
not const
for (; *s; s++)
cout << *s << endl;

char* const t = "welcome"; // const pointer
int i = 0;
// t = "abcd"; // WRONG! t is read-only
for (; *(t+i); i++)
{
if (*(t+i) == 'o') // ????????? I suspect I can do this, but
why
segmentation fault ??????????
*(t+i) = 'a'; // change "welcome" to "welcame"
cout << *(t+i);
}
cout << endl;

Aug 23 '06 #1
7 14710
xg****@gmail.co m wrote:
Hi all! I've taken some time on learning the difference between
"pointers to const variables" and "const pointer variables". The
question is: in the following code, can we change the contents of the
const pointer (i.e. t)? I got a segmentation fault in the last for
loop. Thanks in advance!
It's one of the many weird things in C++. The string literal is always
const, but it converts to a non-const char*, because of some historical
reason I presume. You must not write to a string literal.

By the way, you can cast away constness and than write to an object. It
is perfectly legal do this except when the object was defined const in
the first place. String literals fall under that category.

Jens
Aug 23 '06 #2

xg****@gmail.co m wrote:
Hi all! I've taken some time on learning the difference between
"pointers to const variables" and "const pointer variables". The
question is: in the following code, can we change the contents of the
const pointer (i.e. t)? I got a segmentation fault in the last for
loop. Thanks in advance!

#include <iostream>

using namespace std;

main ()
{
const char* s; // pointer to const variable
s = "hello";
for (; *s; s++)
// *s = 'a'; WRONG! the string is const, so it cannot be
changed
cout << *s << endl;
s = "world"; // OK! reassign s to another string. the pointer is
not const
for (; *s; s++)
cout << *s << endl;

char* const t = "welcome"; // const pointer
int i = 0;
// t = "abcd"; // WRONG! t is read-only
for (; *(t+i); i++)
{
if (*(t+i) == 'o') // ????????? I suspect I can do this, but
why
segmentation fault ??????????
*(t+i) = 'a'; // change "welcome" to "welcame"
cout << *(t+i);
}
cout << endl;
>From the standard, 2.13.4.2: "[...] The effect of attempting to modify
a string literal is undefined."

--
Alan Johnson

Aug 23 '06 #3

Alan Johnson wrote:
xg****@gmail.co m wrote:
Hi all! I've taken some time on learning the difference between
"pointers to const variables" and "const pointer variables". The
question is: in the following code, can we change the contents of the
const pointer (i.e. t)? I got a segmentation fault in the last for
loop. Thanks in advance!

#include <iostream>

using namespace std;

main ()
{
const char* s; // pointer to const variable
s = "hello";
for (; *s; s++)
// *s = 'a'; WRONG! the string is const, so it cannot be
changed
cout << *s << endl;
s = "world"; // OK! reassign s to another string. the pointer is
not const
for (; *s; s++)
cout << *s << endl;

char* const t = "welcome"; // const pointer
int i = 0;
// t = "abcd"; // WRONG! t is read-only
for (; *(t+i); i++)
{
if (*(t+i) == 'o') // ????????? I suspect I can do this, but
why
segmentation fault ??????????
*(t+i) = 'a'; // change "welcome" to "welcame"
cout << *(t+i);
}
cout << endl;
From the standard, 2.13.4.2: "[...] The effect of attempting to modify
a string literal is undefined."
Somehow my reply got partly attached to the quote.

Anyway, consider the consequences if you COULD change a string literal.
char * const p1 = "welcome" ;
p1[4] = 'a' ; // UNDEFINED BEHAVIOR

What should this print? "welcome" or "welcame"
std::cout << "welcome" << std::endl ;

--
Alan Johnson

Aug 23 '06 #4
You are right. I cannot change a string literal. It is right if I do
this before the for loop:
char u[] = "welcome";
char* const t = u;

Aug 23 '06 #5
I got a segmentation fault in the last for loop

The following two programs are equivalent:

Program (1)

int main()
{
"Hello"[2] = 'x';
}
Program (2)

char const __literal1_cons t[] = "hello";

char (&__literal1)[sizeof __literal1_cons t] =
const_cast<char (&)[sizeof __literal1_cons t]>(__literal1_co nst);

int main()
{
__literal1[2] = 'k';
}

--

Frederick Gotham
Aug 24 '06 #6
In article <un************ *******@news.in digo.ie>, fg*******@SPAM. com
says...

[ ... ]
The following two programs are equivalent:
True, but probably not for the reason you believe.
Program (1)

int main()
{
"Hello"[2] = 'x';
}
This has undefined behavior because it attempts to modify a string
literal.
Program (2)

char const __literal1_cons t[] = "hello";
This has undefined behavior because any name with two consecutive
underscores is reserved.

So, the behavior is equivalent, because it's undefined in either case.
OTOH, the two have entirely different sources for their undefined
behavior (yes, I understand what you were trying to get at, but at least
IMO, your explanation obfuscated the point you were trying to make, not
least by adding in unrelated problems).

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 27 '06 #7
Jerry Coffin posted:
>Program (2)

char const __literal1_cons t[] = "hello";

This has undefined behavior because any name with two consecutive
underscores is reserved.

The purpose of my code was to demonstrate what goes on "behind the curtains"
when one uses a string literal in one's code. Therefore, any and all
identifiers which are used will be unique to the implementation.

I thought my code made that obvious.

--

Frederick Gotham
Aug 28 '06 #8

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

Similar topics

23
6658
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
2
6497
by: s88 | last post by:
Hi all: I saw the code likes... 7 #include <stdio.h> 8 int main(void){ 9 const char *const green = "\033[0;40;32m"; 10 const char *const normal = "\033[0m"; 11 printf("%sHello World%s\n", green, normal); 12 return 0; 13 }
9
1269
by: Gary | last post by:
Hi all! I've taken some time on learning the difference between "pointers to const variables" and "const pointer variables". The question is: in the following code, can we change the contents of the const pointer (i.e. t)? I got a segmentation fault in the last for loop. I wrote the code in c++, but the language is not the point, right? :) Thanks in advance! #include <iostream>
26
11791
by: =?gb2312?B?wNbA1rTzzOzKpg==?= | last post by:
i wrote: ----------------------------------------------------------------------- ---------------------------------------- unsigned char * p = reinterpret_cast<unsigned char *>("abcdg"); sizeof(reinterpret_cast<const char *>(p)); ----------------------------------------------------------------------- ---------------------------------------- the compiler tells me that "reinterpret_cast from type "const char * " to type "unsigned char *"...
7
3057
by: Bill Davy | last post by:
I want to be able to write (const char*)v where v is an item of type Class::ToolTypeT where ToolTypeT is an enumeration and I've tried everything that looks sensible. There's an ugly solution, but surely this is possible? I could define an operator<< but for various reasons, I really want to convert to a 'const char*' (to embed into a string which becomes part of a window's caption, etc).
0
9944
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
9796
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,...
0
10757
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10420
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
9583
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7134
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();...
1
4620
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
4225
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3239
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.