Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a character in a string using pointers?

Tags:

c

pointers

im having troubles with this code

int main() {
     char *My_St = "abcdef";
     *(My_St+1)='+';
     printf("%s\n",My_St);
     return 0;
}

i built this code and has no errors, but when i try to run it, it throws a segmentation fault, could someone tell what's wrong

like image 794
jack Avatar asked May 03 '26 08:05

jack


1 Answers

You can't because you are trying to modify const data.

change it to:

char My_St[] = "abcdef";

Then you will be able to change it.

Think about what you were doing, you were declaring a pointer that pointed to "abcdef". It IS a pointer, not an array of chars. "abcdef" lives in the farm, I mean, in the .text area of your program and that is immutable.

When you do it the way I've shown, you are telling the compiler: i'm declaring this array, that will have as many chars as are needed to accommodate "abcdef" and also, as you are there, copy "abcdef" to it.

like image 114
Vinicius Kamakura Avatar answered May 04 '26 21:05

Vinicius Kamakura



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!