You can (in general) use the expression (*ptr)++
to change the value that ptr
points to when ptr
is a pointer and not an array (ie., if ptr
is declared as char* ptr
).
However, in your first example:
char *ptr = "Hello!"
ptr
is pointing to a literal string, and literal strings are not permitted to be modified (they may actually be stored in memory area which are not writable, such as ROM or memory pages marked as read-only).
In your second example,
char ptr[] = "Hello!";
The array is declared and the initialization actually copies the data in the string literal into the allocated array memory. That array memory is modifiable, so (*ptr)++
works.
Note: for your second declaration, the ptr
identifier itself is an array identifier, not a pointer and is not an 'lvalue' so it can't be modified (even though it converts readily to a pointer in most situations). For example, the expression ++ptr
would be invalid. I think this is the point that some other answers are trying to make.