3

Consider the following code

#include<stdio.h>
int main()
{
    int a[5];
    int *ptr=a;
    printf("\n%u", &ptr);
    ++ptr;
    printf("\n%u", &ptr);
}

On Output I'm getting same address value, Why pointer address is not incrementing.

2
  • 3
    &ptr takes the ADDRESS of the pointer, which doesn't change. you're incrementing whatever the pointer is pointing at. Commented May 19, 2015 at 20:42
  • an address is displayed using "%p" not "%u" (which is for an insigned int) Commented May 19, 2015 at 23:47

3 Answers 3

11

The pointer is being incremented. The problem is that you are looking at the address of the pointer itself. The address of a variable cannot change. You mean to look at the value of the pointer, that is, the address it stores:

printf("\n%p", ptr);
Sign up to request clarification or add additional context in comments.

Comments

3

On Output I'm getting same address value, Why pointer address is not incrementing.

The value of ptr is different from address of ptr.

By using ++ptr;, you are changing the value of ptr. That does not change the address of ptr. Once a variable is created, its address cannot be changed at all.

An analogy:

int i = 10;
int *ip = &ip;
++i; // This changes the value of i, not the address of i.
     // The value of ip, which is the address of i, remains
     // same no matter what you do to the value of i.

Comments

0

Let's go through the basics.

When you declare a pointer variable, you use a * with the type of whatever is being pointed to.

When you dereference a pointer (take the value this pointer is pointing to), you put * before it.

When you get the address of something (an address which can be stored in a pointer variable), you put & before whatever you're trying to get the address of.

Let's go through your code.

int *ptr=a; - ptr is a pointer-to-int, pointing to the first element of a.

printf("\n%u", &ptr); this prints the address of ptr. As ptr is a pointer, &ptr is a pointer-to-pointer. That is not what you wanted to see (as I understand), and you'd need to remove &.

++ptr; you inscrease the value of ptr, which is all right, but

printf("\n%u", &ptr); will still output the same thing, because although the contents of the pointer ptr have changed, its address has not.

So, you just need to replace each of the printf calls with printf("\n%u", ptr); to get the desired results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.