473,807 Members | 2,851 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 14706
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
6648
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
2
6493
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
11775
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
3054
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
10372
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...
1
10374
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
10112
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
9193
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...
1
7650
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
6879
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
5546
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...
2
3854
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
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.