Click here to Skip to main content
15,889,403 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C
int main(){
int  a[5];
int *ptr;
ptr=a;
for(int i=0;i<5;i++){
scanf("%d",ptr);
printf("%p\n",&ptr+i);
ptr++;}}

Output:
0x7fff1e80ea58
0x7fff1e80ea60
0x7fff1e80ea68

but if am trying to put
C
printf("%p",&ptr);

then i am getting the output as
Output:
0x7fff1e80ea58
0x7fff1e80ea58
0x7fff1e80ea58

Why ?

What I have tried:

I hav tried to replace ptr with a
Posted
Updated 27-May-22 22:23pm
v2

First off, always indent and space your code, even in a little scrap of program like this - it makes it a lot easier to read:
C
int main()
    {
    int  a[5];
    int *ptr;
    ptr = a;
    for(int i = 0;i < 5; i++)
        {
        scanf("%d", ptr);
        printf("%p\n", &ptr + i);
        ptr++;
        }
    }
The difference between
C
printf("%p\n", &ptr + i);
and
C
printf("%p\n", &ptr);
is obvious: in one you add a variable value i to static value &ptrand in the other you don't.

Think about it: ptr is a variable which contains the address of an array element in memory - but as a variable it is also stored somewhere, so it has it's own address &ptr which doesn't change when you alter the value the variable contains.

Try this:
C
int main()
    {
    int  a[5];
    int *ptr;
    ptr = a;
    printf("%p\n", ptr);
    printf("%p\n", a);
    printf("%p\n", &ptr);
    printf("%p\n", &a);
    }

And see what you get.
 
Share this answer
 
Try
C
#include <stdio.h>
  
int main()
{
  int  a[5];
  int *ptr = a;
  for(int i=0; i<5; i++)
  {
    scanf("%d",ptr);
    printf("address of pointer %p, address of pointed value %p, value %d\n", &ptr, ptr, *ptr);
    ptr++;
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900