Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing one char in a c string

Tags:

arrays

c

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.

like image 447
yotamoo Avatar asked Sep 25 '11 18:09

yotamoo


People also ask

Can you change a char in a string?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

Can we change character in string in C?

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.

How can I replace a single character in a string in C#?

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.

How do you change the first character of a string?

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.


1 Answers

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.

like image 120
bdonlan Avatar answered Sep 27 '22 23:09

bdonlan