Could you explain to me what's the difference between these expressions?
Code:p++;Code:(*p)++;(assuming p as a pointer)Code:*(p++);
Thanks
Could you explain to me what's the difference between these expressions?
Code:p++;Code:(*p)++;(assuming p as a pointer)Code:*(p++);
Thanks
Last edited by ekosix; 05-19-2010 at 07:08 PM. Reason: fix title
The first adds one to the pointer itself (making it point somewhere else). The second adds one to the value pointed to by p. The third moves the pointer, then gets the (new) value pointed to.
Code:I think so the following example will solve ur doubts #include <stdio.h> main(){ int *p; int c; c = 12; p = &c; printf("%d\n", *p); // this will print the value which it points // printf("%d\n", p++); // this wil point to some location printf("%d\n", (*p)++); // this will print the original value which it points and then it increments printf("%d\n", *(p++)); // this will print the one time original value and address of p gets incremented printf("%d\n", *(p++)); // since address of p gets incremented it will print some value in it return 0; } -------------------- the output is 12 12 13 -1074905056
To clarify:
p++ is post increment, which means after the expression is evaluated (++p is pre increment). So the first time p++ is called, p's address increases by the unit size of it's type, in this case an int. In the case of sivanihonjin's code, this is now out of bounds so this should not have been done. Subsequently accessing p's value may cause a segmentation fault. If not, you will get whatever value happens to be where p is pointing to.Code:printf("%d\n", *(p++)); // this will print the one time original value and address of p gets incremented printf("%d\n", *(p++)); // since address of p gets incremented it will print some value in it
Last edited by MK27; 05-21-2010 at 07:28 AM.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
ThanKs for your suggestion:
Yes its true.
p's value may cause a segmentation fault. If not, you will get whatever value happens to be where p is pointing to.
To be pedantic, it's not the value that causes the segfault. It's the dereferencing of the pointer that causes it. (i.e.: trying to access something you shouldn't)
Quzah.
Hope is the first step on the road to disappointment.