C | Advanced Pointer | Question 9

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
#include <stdlib.h>
  
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);
    printf("%d ", *++ptr);
    printf("%d ", ++*ptr);
}

chevron_right


(A) Compiler Error
(B) 0 1 2 2 3
(C) 0 1 2 3 4
(D) 1 2 3 4 5


Answer: (B)

Explanation: The important things to remember for handling such questions are

1) Prefix ++ and * operators have same precedence and right to left associativity.

2) Postfix ++ has higher precedence than the above two mentioned operators and  associativity is from left to right.

We can apply the above two rules to guess all

*ptr++ is treated as *(ptr++)

*++ptr is treated as *(++ptr)

++*ptr is treated as ++(*ptr)

Quiz of this Question



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.