The program is:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *a="abc",*ptr;
ptr=a;
ptr++;
*ptr='k';
printf("%c",*ptr);
return 0;
}
The problem is in the
*ptr='k';
line, when I remove it program works normally. But I can’t figure out the reason.
The problem is because you are trying to change the string literal
"abc"with:That’s undefined behaviour. The standard explicitly states that you are not permitted to change string literals as per section
6.4.5 String literalsof C99:It will work if you replace:
with:
since that copies the string literal to a place that’s safe to modify.