I am trying to understand why the following code is illegal:
int main ()
{
char *c = "hello";
c[3] = 'g'; // segmentation fault here
return 0;
}
What is the compiler doing when it encounters char *c = "hello";
?
The way I understand it, its an automatic array of char, and c
is a pointer to the first char. If so, c[3]
is like *(c + 3)
and I should be able to make the assignment.
Just trying to understand the way the compiler works.
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
you are trying to change a string literal which is undefined behavior in C. Instead use string1[]="hello"; Segmentation fault you get is because the literal is probably stored in the the read only section of the memory and trying to write to it produces undefined behavior.
ToString(); You can't change string's characters in this way, because in C# string isn't dynamic and is immutable and it's chars are readonly. For make sure in it try to use methods of string, for example, if you do str. ToLower() it makes new string and your previous string doesn't change.
To replace the first character in a string:Use the String. replace() method to replace the character in the string. The replace method will return a new string with the first character replaced.
String constants are immutable. You cannot change them, even if you assign them to a char *
(so assign them to a const char *
so you don't forget).
To go into some more detail, your code is roughly equivalent to:
int main() {
static const char ___internal_string[] = "hello";
char *c = (char *)___internal_string;
c[3] = 'g';
return 0;
}
This ___internal_string
is often allocated to a read-only data segment - any attempt to change the data there results in a crash (strictly speaking, other results can happen as well - this is an example of 'undefined behavior'). Due to historical reasons, however, the compiler lets you assign to a char *
, giving you the false impression that you can modify it.
Note that if you did this, it would work:
char c[] = "hello";
c[3] = 'g'; // ok
This is because we're initializing a non-const character array. Although the syntax looks similar, it is treated differently by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With