AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumcpointers

~90s

Pointer arithmetic against value arithmetic

What does this C program print?

#include <stdio.h>

int main(void) {
    int a[5] = {10, 20, 30, 40, 50};
    int *p = a + 1;
    printf("%d %d", *(p + 2), *p + 2);
    return 0;
}
Show the answer and the worked solution

Correct answer: B.

40 22

Worked solution

  1. p = a + 1 makes p point at a[1], whose value is 20.
  2. *(p + 2) dereferences two elements further along, which is a[3] = 40.
  3. *p + 2 fetches 20 first and then adds 2, giving 22, so the program prints 40 22.

Answer: 40 22.

The idea

The dereference operator binds tighter than +, so brackets decide whether you are moving through memory or doing plain arithmetic. Pointer addition advances in units of the pointed-to type, never in bytes.

Shortcut. p starts at index 1, so *(p + 2) is index 3, which holds 40; *p + 2 is plain arithmetic on the value, 20 + 2 = 22.

Common trap. "30 22" counts p + 2 from the start of the array, landing on a[2], and forgets that p already points one element in.

Pointer arithmetic against value arithmetic — Aptitude

Pointer arithmetic against value arithmetic: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

int main(void) {
    int a[5] = {10, 20, 30, 40, 50};
    int *p = a + 1;
    printf("%d %d", *(p + 2), *p + 2);
    return 0;
}

Options

  1. 30 22
  2. 40 22
  3. 40 32
  4. 50 22
Show the answer and the worked solution

Correct answer: B. 40 22

Worked solution

  1. p = a + 1 makes p point at a[1], whose value is 20.
  2. *(p + 2) dereferences two elements further along, which is a[3] = 40.
  3. *p + 2 fetches 20 first and then adds 2, giving 22, so the program prints 40 22.

Answer: 40 22.

The idea

The dereference operator binds tighter than +, so brackets decide whether you are moving through memory or doing plain arithmetic. Pointer addition advances in units of the pointed-to type, never in bytes.

Shortcut. p starts at index 1, so *(p + 2) is index 3, which holds 40; *p + 2 is plain arithmetic on the value, 20 + 2 = 22.

Common trap. "30 22" counts p + 2 from the start of the array, landing on a[2], and forgets that p already points one element in.

All Programming Fundamentals questions · placement mock tests