15,501,490 members
1.00/5 (1 vote)
See more:
```#include<stdio.h>
int main(){

int a=10; //initilising a as 10
int *p;   //pointer p

p=&a;     //holds the address of a

printf("p=%d\n*p=%d",p,*p);

printf("\np=%d",p+1);
printf("\n*p=%d",*(p+1));  //here i am facing the problem to get the value at p+1

return 0;
}```

What I have tried:

I was learning about pointer and I was struct with the pointer arithmetic .I have understood that the if we de p=p+1 then the address at the p pointer will be increased by 4 as it is an integer but if we want to find the value at the p+1 that is *(p+1) that is the problem I am facing with different result each time . Please explain me the working of it in the Ans and how to calculate the value . and also I am also confused that the Ans will be garbage or something else. Till now when I apply my logic according to me the value at that address is not having any value assigned to p+1.please Ans
Posted
Updated 4-Aug-21 21:51pm

## Solution 1

The problem is simple: `a` is any integer. It contains a value, which you can print.
But `p + 1` move away from`a` completely, and advances to the next integer - which hasn't been defined, and contains no value you are aware of. What do you expect it to print? It hasn't been allocated, so it doesn't even have a default value!

Change `a` to a small array of values, set them all, and then use pointer arithmetic to advance through them. When you start pointing to undefined memory, you start to get a lot of problems ...

vishal kumawat 15-May-21 3:16am
Thanks @OriginalGriff I got our point
OriginalGriff 15-May-21 3:32am
You're welcome!

## Solution 2

A few tips :

You should try this experiment again but this time make a an array and while you're at it, give it values :
C++
`int a[ 5 ] = { 0, 1, 2, 3, 4 };`
You can also move the pointer. This statement is valid : `++p;` Try it and see the results. `--p;` is also valid, but will point to invalid memory if `p` equals the address of `a[0]`.

I prefer to see addresses in hex so I use a statement like this to display them :
C++
`printf( "p=%08X\n", p );`
So, combining all this together and making a function out of it can result in this code :
C++
```void displayPointer( int * p, int a[] )
{
printf( "  p=%08X, value is %d\n", p, * p );
printf( "p+1=%08X, value is %d\n", p+1, *(p+1) );

printf( "incrementing pointer\n" );
++p;
printf( "  p=%08X, value is %d\n", p, * p );

printf( "decrementing pointer\n" );
--p;
printf( "  p=%08X, value is %d\n", p, * p );
}

int main()
{
int a[ 5 ] = { 0, 1, 2, 3, 4 };
int * p;

p = & a[ 0 ];
printf( "p is address of a[ 0 ] :\n" );
displayPointer( p, a );

p = & a[ 2 ];
printf( "p is address of a[ 2 ] :\n" );
displayPointer( p, a );
return 0;
}```
Try running this and observe the results.