The following code gives a seg fault at second line:
char *tester = "hello";
char a = (*tester)++; // breaks here
printf("Char is %c\n", a);
The following code works:
char *tester = "hello";
a = *tester;
a++;
printf("Char is %c\n", a);
// prints i
Why can't it be done in one operation?
It can be, you're just incrementing the wrong thing. (*tester)++
increments the data to which tester
is pointing. I believe what you wish to do is *(++tester)
which will increment the pointer and then dereference it.
char *tester = "hello";
Here tester is pointing to a string constant. It is stored in a read-only memory. Any write modifications causes undefined behavior.
As @Taelsin pointed, it seems you want to increment the pointer itself, and not what it is pointing to. You need *(++tester).
After OP's clarification:
In case you want to increment the H to I, then (*tester + 1) would do the job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With