I have a question is *++p and ++*p legal expressions i have seen *++p used however i have not seen ++*p put in to use
Printable View
I have a question is *++p and ++*p legal expressions i have seen *++p used however i have not seen ++*p put in to use
Yes, they're both legal. One alters the address of p and then dereferences (which is kind of useless by itself), and the other dereferences p and then alters the result.
if i had
char a[ ] = "cba", *p = a;
then ++*P would b equal to c right??i am confused now
the value thats stored in p (*p) would be the first element in the array, so it would be 'c'. if you increment this value (++*p) it will add one to 'c' so the result is 'd'
Start slowly when going through it. First let's turn it into a program:
Output:Code:#include <stdio.h>
int main(void)
{
char a[ ] = "cba";
char *p = a;
printf("*p = %c\n",*p);
++*p;
printf("*p = %c\n",*p);
return 0;
}
So why?Code:*p = c
*p = d
Basically you have an array of chars that are like this in memory:
You set p to point to this array. That means p holds the address of a, and can be treated in some ways as if it's a.Code:'c', 'b', 'a', '\0'
Arrays are kind of special when you consider how the relationship they share with pointers. When you use an array name, you're usually referencing a pointer to the first element of the array. This is important. Pointing p to a actually points p at the first element of a.
So what does ++*p do?
First of all, it takes p, and dereferences it, and then performs the ++ on whatever the result was. This is equivalent of typing this out:
This means that you're grabbing where p points at and altering what it points at to be one more than it used to be.Code:++(*p);
Since p points at the memory location of letter c inside the array, you end up ++ing the letter c. This causes c to be d, and the array a to look like this in memory:
Hope this helps.Code:'d', 'b', 'a', '\0'
Edit: Oh, well, beaten again. lol.. :(