Atinesh
Atinesh

Reputation: 1910

Why Pointer is not incrementing?

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.

Upvotes: 3

Views: 989

Answers (3)

user3079266
user3079266

Reputation:

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.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

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.

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227390

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);

Upvotes: 11

Related Questions