#include<stdio.h>
main()
{
char c = 'R';
printf("%c\n",c);
c++;
printf("%c\n",c);
char *ptr ="Ramco Systems";
printf("%c\n",(*ptr));
(*ptr)++;
printf("%d\n",(*ptr));
}
The output of the first, second ,3rd printf are ‘R’, ‘S’ & ‘R’ (as expected). However the line “(*ptr)++;” gives runtime error. Can someone explain why ?
The reason is because the memory pointed to be
ptrwas set at compiletime and is non-modifiable.So accessing the first character via
*ptris fine and returnsR, but attempting to increment the first character yields a runtime error because you are not allowed to modify strings that you provide at compiletime.To expand on Seg Fault’s comment below, a better way to write your code would have been:
Notice how in this new code, the declared pointer type is more accurate and as a result the compiler is able to give a compiletime error on the second line (much better than a runtime error).