tuhin panda
tuhin panda

Reputation: 31

how value of a pointer is same even after incrementing the address, for variable its different

In the below program I am getting same value for different pointer operations:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

int main(void) {
    int i;
    int *ptr = (int *)malloc(5 * sizeof(int));

    for (i = 0; i < 5; i++)
        *(ptr + i) = i;

    printf("%d ", *ptr++);
    printf("%d ", (*ptr)++); 
    printf("%d ", *ptr); ---------> o/p: 2
    printf("%d ", *++ptr);--------> o/p: 2
    printf("%d ", ++*ptr);
}

Output: 0 1 2 2 3

My doubt is how *ptr and *++ptr is printing same value. It should be different as we incrementing the pointer address

The post- and pre-increment for a variable I can understand, here both are pre-increment

Upvotes: 2

Views: 80

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

With (*ptr)++), you increment the value to which ptr points, such that your "array" contains two equal values then, i.e. ptr[0]==2 and ptr[1]==2. That's why *ptr and *++ptr yield the same value, though they point to different addresses.

Remove the printf("%d ", (*ptr)++) and you'll see clearer.

Upvotes: 5

Related Questions