pointer tricky problem

I cannot figure out what is happening in the background and the code breaks. I was hoping that ++(*p) would print the next character which is 'b' ('a'+1 yields 'b'). So, what is it really doing the ++(*p) command?

++(*p) , ++*p are these two equivalent?
1
2
3
4
5
6
  char *p,  *a[1]={"ac"};// an array of pointers with one array element string

    p=a[0];
    printf("%c\n",*p );

    printf("%c", ++(*p) );
Last edited on
[DELETED]

Sorry, bad advice.
Last edited on
boost lexical cast wrote:
You cannot initialize a pointer with a string literal.
Sure, no problem with that.

The problem is that a string literal (such as "ac") is const char *, while unfortunately the compiler accept it as char *.

The string literal is stored in the read only memory. ++(*p) tries to modify the const memory and thus fails.

mynicks wrote:
++(*p) , ++*p are these two equivalent?
This depends on the precedence and associativity. See:

http://en.cppreference.com/w/cpp/language/operator_precedence

So it is rather wise to use parenthesis.


boost lexical cast wrote:
When you do ++(*p) that increments the value of the object p is pointing (because of that deference operator).
This is what the op wants to do.
Topic archived. No new replies allowed.