Replace individual character element of a string C

2019-03-25 03:02发布

问题:

This question already has an answer here:

  • How to replace specific characters in a string with other characters 3 answers

I am trying to do something really basic on C but I keep getting a segmentation fault. All I want to do is replace a letter of a word with a different letter- in this example replace the l with a L. Can anyone help explain where I have gone wrong? It should be a really basic problem I think, I just have no idea why its not working.

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
    char *string1;

    string1 = "hello";
    printf("string1 %s\n", string1);    

    printf("string1[2] %c\n", string1[2]);
    string1[2] = 'L';
    printf("string1 %s\n", string1);

    return 0;
}

For my output I get

string1 hello
string1[2] l
Segmentation fault

Thanks!

回答1:

string1 = "hello";
string1[2] = 'L';

You can't change string literals, it's undefined behavior. Try this:

char string1[] = "hello";

Or maybe:

char *string1;
string1 = malloc(6); /* hello + 0-terminator */
strcpy(string1, "hello");

/* Stuff. */

free(string1);


回答2:

char *string1;
string1 = "hello";

string1 points to a string literal and string literals are non-modifiable.

What you can do is initialize an array with the elements of a string literal.

char string1[] =  "hello";

the elements of string1 array are modifiable.



回答3:

char *string1 = "hello";

When running the code, the string literal will be in a section that is read-only. OS does not allow the code to change that block of memory, so you get a seg-fault.

char string1[] = "hello";

The string literal will be pushed onto the stack when you run the code.



回答4:

 string1[2] = 'L';

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.