Just after confusing myself on it and wrecking my head:
Code:int x =6; int *p=&x printf("%d", (*p+6)) //gives me 12; printf("%d", *p) //should give 12 also?? if i did: printf("%d", (*p+=)) //gives me 7 should it?;
Just after confusing myself on it and wrecking my head:
Code:int x =6; int *p=&x printf("%d", (*p+6)) //gives me 12; printf("%d", *p) //should give 12 also?? if i did: printf("%d", (*p+=)) //gives me 7 should it?;
I am just a beginner at C so perhaps this is irrelevant.
should you not initialise the pointer like this:Code:int x =6; int *p=&x
Code:int x = 6; int *p; p = &x;
Instead of asking about code that is obviously mistyped and couldn't possibly produce any output at all, why not post the real code that gives you this output.
Code:#include <stdio.h> int main(void) { int i = 6; int* p = &i; printf("%d\n", *p + 6); /* 12 */ printf("%d\n", *p); /* 6 */ printf("%d\n", ++*p); /* 7 NB! *++p would be a serious error */ printf("%d\n", *p); /* 7 */ return 0; }
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
p is a pointer which points to x. Now *p will give the value of x, and *p+6 will give x+6 which is nothing but 12. Again *p is same as x thus 2nd printf prints 6 not 12.
For the 3rd printf I'm assuming you meant *p++(forgot the shift key), since ++ and * have the same precedence and right to left associativity thus p++ is done first and then the value at that address which is nothing but value at the address where p was pointing, thus printing 6. But now p points to a different address, so a 4th printf will give *p=some garbage value.
HOPE YOU UNDERSTAND.......
By associating with wise people you will become wise yourself
It's fine to celebrate success but it is more important to heed the lessons of failure
We've got to put a lot of money into changing behavior
PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
IDE- Microsoft Visual Studio 2008 Express Edition