954,487 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

char pointer in C

Hi,

I am a newbie in C and have this question with char pointer;

char * s = "hello world";
*(s+1) = 'a';


This is throwing a segfault error. Should'nt this work since I am modifying only one memory location. Also I have seen such code on the net. I am using GCC compiler.

see_bharath
Newbie Poster
1 post since Dec 2011
Reputation Points: 10
Solved Threads: 0
 
Should'nt this work since I am modifying only one memory location.


No, it shouldn't work because string literals aren't modifiable.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

instead of working on char.... in cpp there is a string. very flexible and you can easily do that.

string foo = "hello";
foo +=" world";
std::cout << foo;
// out put 
hello world
richieking
Master Poster
764 posts since Jun 2009
Reputation Points: 61
Solved Threads: 152
 

This will work ok because it isn't trying to change a string literal

char s[] = "hello world";
*(s+1) = 'a';
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Ancient Dragon is correct. In your original example, s is a char*, but string literals are const char*, and non-mutable - usually the compiler assigns them to read-only memory. The way that AD did it, to declare s as an array, means that the compiler will take the string literal as an initializer for an array that is in writable memory. IE, it gives the same result as this:

char s[12] = { 'h','e','l','l','o',' ','w','o','r','l','d',0 };

but the way AD did it is a LOT easier!

rubberman
Posting Virtuoso
1,564 posts since Mar 2010
Reputation Points: 277
Solved Threads: 179
 

Enable ISO C++ conformance (eg. --std=c++0x -pedantic) and warning messages (eg. -Wall).

char * s = "hello world";


would have made the compiler emit a diagnostic - something like
"warning: deprecated conversion from string constant to char*".

vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

Now hold on though: the OP referred to C rather than C++. It is possible that this was supposed to be posted in the C forum. While this wouldn't change Narue's answer (or Ancient Dragon's), the replies which assume C++ strings wouldn't apply.

Schol-R-LEA
Posting Pro
556 posts since Oct 2010
Reputation Points: 254
Solved Threads: 85
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You