0

I have this simple C code:

char *foo = "ABCDEFGH";
foo[2] = 'Z';
printf("%s\n", foo);

I expect the output is:

ABZDEFGH

I got this error:

Segmentation fault

I know char * is pointer and different with char[]. In my real project, foo is variable that come from function that return char *. That's why I ask.

The question is how do I achieve what I expect in output?

Citra Dewi
  • 213
  • 3
  • 12
  • 1
    `char *foo = "ABCDEFGH";` is a pointer to a string literal - you are not allowed to modify a string literal. You need to first copy it to something that can be modified, e.g.: `char foo[] = "ABCDEFGH";` – UnholySheep Jul 31 '22 at 10:17
  • 1
    `char foo* =` is not valid syntax – Mat Jul 31 '22 at 10:18
  • 1
    You are not compiling the same piece of code shown in the question. – David Ranieri Jul 31 '22 at 10:19
  • @UnholySheep according duplicate question refference _will place "Hello world" in the read-only parts of the memory, and making s a pointer to that makes any writing operation on this memory illegal._ But I'm working on embedded system, I wonder if such illegal is just Operating System rules? – Citra Dewi Jul 31 '22 at 10:20
  • Whether it works or not is dependent on whether the string literal will be in read-only memory or not. On some platforms it might work, but on many it will not. You should know the embedded system you're developing for. It appears to me that you skipped the basics. – Cheatah Jul 31 '22 at 11:12

0 Answers0