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.

Recommended Answers

All 6 Replies

Should'nt this work since I am modifying only one memory location.

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

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

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

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

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!

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*".

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.