I am trying to replace 'G'
with 'R'
but I am getting unhandled exception.
int main()
{
char *pszStr1 = "EFGH";
(++pszStr1)[1] = 'R';
printf("%s", pszStr1);
return 0;
}
I am trying to replace 'G'
with 'R'
but I am getting unhandled exception.
int main()
{
char *pszStr1 = "EFGH";
(++pszStr1)[1] = 'R';
printf("%s", pszStr1);
return 0;
}
Your string lies in a read-only area.
Instead, do
int main()
{
static char pszStr1arr[] = "EFGH";
char *pszStr1 = pszStr1arr;
(++pszStr1)[1] = 'R';
printf("%s", pszStr1);
return 0;
}
int main()
{
char *pszStr1 = "EFGH";
(++pszStr1)[1] = 'R';
printf("%s", pszStr1);
return 0;
}
In this code pszStr1
is a string literal, which must be considered as const char *pszStr1 = "EFGH";
. You're trying to modify a read-only memory space.
char *pszStr1 = "EFGH";
Is a string literal, but here it is like you wrote : const char* pszStr1 = "EFGH";
You are trying to modify a read-only memory-space...
You can solve it simply by changing it into :
char pszStr1[] = "EFGH";
char *pszStr1 = "EFGH";
is kept on readonly section of the executable. Compiler internally allocates the string "EFGH" then makes pszStr1 point to it. So, you can't change it. Use array instead of char pointer, like below:
char pszStr1[] = "EFGG";
char *pszStr1 = "EFGH";
is a constant and it is undefined, if you change the content.
If you want to change the content, you have to take an array:
char arr[] = "EFGH";
and you are able to do this:
arr[2] = 'R';
String literals are const in modern C, so the declaration char *pszStr1 = "EFGH";
is wrong, it should be const char *pszStr1 = "EFGH";
. In many operating systems they end up in a section in memory that is marked as readonly, and the OS enforces that you can't write to them. If you copy the string literal to a temporary string on the stack (or heap), the program works.
int main()
{
char str[5];
char *pszStr1=str;
strcpy(pszStr1,"EFGH");
(++pszStr1)[1] = 'R';
printf("%s", pszStr1);
return 0;
}