I am wondering if one could change the string stored in a variable, without changing the address. And I am unable to write the code to do this, since when I write codes like
char* A = "abc";
char* B = "def";
A = B; <-- if I write down this code, then A will point to B and address changes.
So does anyone know how to do this, changing the string stored in A
to "def"
,without changing the initial address of A
?
Moreover, I have tried to change only one word in variable A
, again, without changing the address.
To do this, I have write the following failure code. BUT I don't know why it fails.
#include <stdio.h>
#include <string.h>
int main(void)
{
char* s = "ABC";
// print value and address of s.
printf("Value of s is %s \n", s);
printf("Address of s is %p \n", s);
s[0] = 'v';
printf("Value of s is %s \n", s);
printf("Address of s is %p \n", s);
}
Using gdb, I figure out that s[0] = 'v'
is invalid and lead to segmentation fault. Why is it the case? Can anyone tell me the reason behind this as well?
Thanks.