MadHatter
MadHatter

Reputation: 680

C pointer behaviour, Volume II

Look at this:

int main() {

char *verse = "zappa";
printf("%c\n", *verse);
// the program correctly prints the first character

*verse++;
printf("%c\n", *verse);
// the program correctly prints the second character, which in fact lies 
// in the adjacent memory cell

(*verse)++;
printf("%c\n", *verse);
// the program doesn't print anything and crashes. Why?

return 0;
}

Why does my program crash as I try to increment the value pointed by verse? I was expecting something like the next character in the ASCII table.

Upvotes: 1

Views: 49

Answers (2)

Barmar
Barmar

Reputation: 781858

verse points to a string literal, which you're not allowed to modify. Try:

char verse1[] = "zappa";
char *verse = verse1;

Now your code will work because verse1 is a modifiable string.

Note that *verse++ is effectively equivalent to just verse++. The indirection returns the value pointed to by the pointer before the increment, but since you're not doing anything with the return value of the expression, the indirection doesn't really do anything.

Upvotes: 3

Bill Lynch
Bill Lynch

Reputation: 81976

This line (*verse)++; modifies a string literal. That is undefined behavior.

Note that the earlier line of code *verse++ is parsed as *(verse++)

Upvotes: 10

Related Questions