Why isn't the pointer incremented?

Consider the following code

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

      

I get the same address value in the output. Why is the pointer address not incremented.

+3


source to share


3 answers


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



printf("\n%p", ptr);

      

+11


source


I get the same address value in the output. Why is the pointer address not incremented.

The value ptr

is different from the address ptr

.

By using ++ptr;

, you change the value ptr

. It doesn't change the address ptr

. After creating a variable, its address cannot be changed at all.



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.

      

+3


source


Go through the basics.

When you declare a pointer variable, you use *

with the type of what it points to.

When looking for a pointer (take the value that pointer points to), precede it *

.

When you get the address of something (an address that can be stored in a pointer variable), you put &

before what you are trying to get to the address.

Pass your code.

int *ptr=a;

- ptr is a pointer to an int pointing to the first element a

.

printf("\n%u", &ptr);

displays the address ptr

. Since ptr

is a pointer, &ptr

is a pointer to a pointer. This is not what you wanted to see (as I understand it) and you need to delete &

.

++ptr;

you increase the value ptr

, everything is fine, but

printf("\n%u", &ptr);

will output the same thing because although the contents of the pointer have ptr

changed, its address does not.

So, you just need to replace each of the calls printf

with printf("\n%u", ptr);

to get the results you want.

0


source







All Articles