Skip to main content

Command Palette

Search for a command to run...

A solved exercise

Updated
•2 min read•View as Markdown

This program combines dereferencing, pre- / post- increment and assignment operations. Try figuring out the output yourself first before reading the output and explanation.

Program:

#include <stdio.h>
int main()
{
 int A[] = {10, 20, 30, 40, 50};
 int *p, i;
 p = A;
 printf("*p : %i\n\n", *p);
 i = *(p++);
 printf("i is: %i\n", i);
 printf("*p is: %i\n\n", *p);
 i = (*p)++;
 printf("i is: %i\n", i);
 printf("*p is: %i\n\n", *p);
 i = *(++p);
 printf("i is: %i\n", i);
 printf("*p is: %i\n\n", *p);
 i = ++(*p);
 printf("i is: %i\n", i);
 printf("*p is: %i\n\n", *p);
 return 0;
}

Output:

Explanation:

#include <stdio.h>
int main()
{
    int A[] = {10, 20, 30, 40, 50};
    int *p, i;
    p = A;
    printf("*p : %i\n\n", *p); // prints a[0]
    printf("*************\n");

    i = *(p++);
    printf("i is: %i\n", i);
    /* Explanation:
    The execution of this statement involves the following operations:
    1. *p dereferencing p to reach a[0]
    2. i=*p which is equivalent to i=a[0], so i =10
    3. Post increment p. So mow p points to a[1].
    */
    printf("*p is: %i\n\n", *p);   //prints a[1]
    printf("*************\n");

    i = (*p)++;
    printf("i is: %i\n", i);
    /* Explanation:
    The execution of this statement involves the following operations:
    1. *p dereferencing p to reach a[1]
    2. i=*p which is equivalent to i=a[1], so i = 20
    3. Post increment *p, that is, post increment a[1].
        a[1] becomes 21
        p still points to a[1].
    */
    printf("*p is: %i\n\n", *p);    //prints a[1]
    printf("*************\n");

    i = *(++p);
    printf("i is: %i\n", i);
    /* Explanation:
    The execution of this statement involves the following operations:
    1. Pre-incrementing p. So now p points to a[2]
    2. i=*p which is equivalent to i=a[2], so i = 30
    */
    printf("*p is: %i\n\n", *p);    //prints a[2]
    printf("*************\n");

    i = ++(*p);
    printf("i is: %i\n", i);
    /* Explanation:
    The execution of this statement involves the following operations:
    1. *p dereferencing p to reach a[2]
    2. ++(*p) is actually ++(a[2]). So a[2] becomes 31
    3. Assign *p (which is same as a[2]) to i. So i is 31.
    */
    printf("*p is: %i\n\n", *p);    //prints a[2], which is now 31.
    return 0;
}

Output:

12 views

More from this blog

P

Programming Tutorials

89 posts