#include <stdio.h>
#include <string.h>
main()
{
char tmpChar;
char *str_1 = "Hello";
int index;
int len = strlen(str_1);
for (int i = 0; i < len/2; i++)
{
index = len - 1- i;
tmpChar = str_1[len - i -1];
str_1[index] = str_1[i]; <<<<<--------------- core dumps at this point. Not sure why
str_1[i] = tmpChar;
printf("str_1[%d] = %c\n", i, str_1[i]);
}
str_1[len] = '\0';
printf("str_1 = %s\n", str_1);
}
#include <stdio.h> #include <string.h> main() { char tmpChar; char *str_1 = Hello; int index;
Share
The ISO C99 standard has this to say about string literals (section 6.4.5/6):
That’s because, typically, all the string literals are lumped into a single area which may be marked read-only, and they’re sometimes merged to save space. In other words, the two string literals:
may be stored thus:
That means: don’t try to modify them. It may work under certain situations but it’s not something that you should rely on if you value portability even a little.
Change:
to:
since this is effectively the same as: