Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indirection and Increment Operator evaluvation

Tags:

c

pointers

#include <stdio.h>

int main() {
    int op9=9;
    int op99=99;
    int op999=999;
    int op9999=9999;

    int *ptr1=&op9,*ptr2=&op99,*ptr3=&op999,*ptr4=&op9999;

    *ptr1++;
    ++*ptr2;
    (*ptr3)++;
    *++ptr4;

    printf("%d=ptr1 \t %d=ptr2 \t %d=ptr3 \t %d=ptr4",ptr1,ptr2,ptr3,ptr4);

    printf("\n %d = *ptr++ \n %d = ++*ptr \n %d = (*ptr)++ \n %d = *++ptr",*ptr1,*ptr2,*ptr3,*ptr4);

    printf("\n \n  %d=ptr1 \t %d=ptr2 \t %d=ptr3 \t %d=ptr4",ptr1,ptr2,ptr3,ptr4);

    return 0;
}

This is the Output I get

-

    209002336=ptr1   -209002344=ptr2     -209002348=ptr3     -209002348=ptr4

-209002348 = *ptr++ 
     100 = ++*ptr 
     1000 = (*ptr)++ 
     1000 = *++ptr4

      -209002336=ptr1    -209002344=ptr2     -209002348=ptr3     -209002348=ptr4

Why does *ptr++ which is a ptr1 point to ptr3's Address? and why does *++ptr4 have a value 1000 which is ptr3's value?

I thought *ptr1++ will point to the next address and since its not part of my program I expected the program to crash. Similarly *++ptr4 should also do the same because its evaluated as *(++ptr4).

So how exactly does Increment and Indirection Operator work for *ptr++ and *++ptr?

like image 666
Abinesh S Prabhakaran Avatar asked Jun 24 '26 12:06

Abinesh S Prabhakaran


1 Answers

Explaining the 1000 = *++ptr4:

Formally, this is undefined behavior.

Practically, the local variables are allocated in the stack consecutively and in reversed order:

int op9;    // SP+3
int op99;   // SP+2
int op999;  // SP+1
int op9999; // SP+0

So by taking a pointer to op9999 and incrementing it, it ends up pointing to op999.

Keep in mind that it is still undefined behavior according to the C-language standard.

This effectively means that you may get different results when using different compilers.

like image 95
barak manos Avatar answered Jun 26 '26 02:06

barak manos