I have been struggling for a few hours with all sorts of C tutorials and books related to pointers but what I really want to know is if it's possible to change a char pointer once it's been created.
This is what I have tried:
char *a = "This is a string";
char *b = "new string";
a[2] = b[1]; // Causes a segment fault
*b[2] = b[1]; // This almost seems like it would work but the compiler throws an error.
So is there any way to change the values inside the strings rather than the pointer addresses?
Thanks
EDIT:
Thanks everyone for your answers. It makes more sense now. It especially makes sense why sometimes it was working fine and other times not working. Because sometimes I'd pass a char pointer and other times a char array (the char array worked fine).
The memory for a & b is not allocated by you. The compiler is free to choose a read-only memory location to store the characters. So if you try to change it may result in seg fault. So I suggest you to create a character array yourself. Something like:
char a[10]; strcpy(a, "Hello");
No, you cannot modify it, as the string can be stored in read-only memory. If you want to modify it, you can use an array instead e.g.
Or alternately, you could allocate memory using malloc e.g.
You could also use
strdup
:For you example: