Skip to content
Related Articles

Related Articles

Improve Article

C | Advanced Pointer | Question 9

  • Difficulty Level : Medium
  • Last Updated : 28 Jun, 2021
Geek Week




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

(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

Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.
My Personal Notes arrow_drop_up
Recommended Articles
Page :