Why I'm getting some garbage value when I increment like this **pptr++ but not for *ptr++? Can anyone help me?
#include<stdio.h>
int main()
{
static int array[] ={9,1,2,3,4};
int *ptr = array;
int **pptr = &ptr;
**pptr++;
printf("%d",**pptr );
*ptr++;
printf("%d",*ptr );
return 0;
}
**pptr++;
and *ptr++;
are incrementing the pointer, not what is pointed at by them.
pptr
is pointing at ptr
, which can be seen as one-element array. Incrementing pptr
will move the pointer to out-of-range and disallow dereferencing that.
ptr
is pointing at the first element of the 5-element array array
. Incrementing ptr
will move the pointer to point at the 2nd element. You are still allowed to dereference this.
The pointer pptr
points to the pointer (object) ptr
due to these declaration.
int *ptr = array;
int **pptr = &ptr;
This expression
**pptr++;
may be rewritten just like
pptr++;
because applying the dereferencing operator does not have an effect.
So now the pointer after incrementing pptr
points to the memory beyond the pointer ptr
and dereferencing it in the following statement
printf("%d",**pptr );
results in undefined behavior.
Instead of these two statements
**pptr++;
printf("%d",**pptr );
you could write just one statement
printf("%d",**pptr++ );
and the output will be
9
though post-incrementing the pointer does not make a sense.
As for these statements
*ptr++;
printf("%d",*ptr );
then again it may be rewritten like
ptr++;
printf("%d",*ptr );
because dereferencing the pointer in this expression *ptr++
does not have an effect.
As the pointer ptr
points to the first element of the array array
then after incrementing it it points to the second element of the array.
Thus this call
printf("%d",*ptr );
outputs
1
To make it more clear you may consider this declaration
int **pptr = &ptr;
as a declaration of a pointer that points to the first element of an array with only single element. Thus incrementing the pointer results that the pointer will point beyond the array with a single element.
Unlike the pointer pptr
the pointer ptr
points to the first element of an array that contains more than one element. So after incrementing the pointer it will point to a valid object: the second element of the array.
That is the difference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.