I have the following code that crashes at the line where I am initializing ch:
char * p = "Test";
char ch = *p++;
printf("Here : %s\n%c", p, ch);
However the following code has no problem:
char * p = "Test";
char ch = *p++;
ch++;
printf("Here : %s\n%c", p, ch);
In the first situation, you’re trying to change the
Tin the “Test” string compiled into the program, which is held in a part of memory that your code isn’t meant to change (usually; there are some environments where it’s allowed, but usually it isn’t). That’s because(*p)++means (loosely speaking)*p = *p + 1(e.g., get the character pointed to byp, increment it, and write it back), and of course,*pis pointing to the compiled-in “Test”.Your second version doesn’t have that problem, because you’re incrementing
ch, which you are allowed to change. Your second version actually increments two different things, in fact; first it doeschar ch = *p++;which retrieves the character at*pand then incrementsp(now it points to the “e” in “Test”), and then you doch = ch++. (You probably meant justch++;there, since++operates directly on its operand.)