character array - Segmentation fault

Hello, thanks for taking the time to look at this.

I'm trying to assign new values to elements of a char array and getting an error as a result.

1
2
char *s = "abcd";
s[1] = 'f';


Why is the second line causing an error? Thanks in advance for any help!
Because s points to a region of memory that is read-only.
There are three ways to prevent this problem:
1. Only assign string literals to 'const char *'s. This way, the compiler will produce an error if you try to do the above. This is the correct way to declare pointers to string literals.
1
2
3
4
//Implicit cast (const char *)->(char *). Left only for compatibility with C. Do not use.
char *s="string literal";
//OK.
const char *s="string literal";
2. If you need to modify the string, declare it like this:
char s[]="string literal";
This is a special syntax for char (and wchar_t) arrays. It means the same as this:
char s[]={'s','t','r', /*...*/,'\0'};
You can now freely modify the string.
3. Use std::strings:
1
2
std::string s="string literal";
s[1]='f';
Last edited on
Hey Helios,

Thanks for the reply and great explanation/tutorial.
Topic archived. No new replies allowed.