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

~120s

sizeof on an array parameter

Assume a machine where int occupies 4 bytes and a pointer occupies 8 bytes. What does this C program print?

#include <stdio.h>

void f(int arr[]) {
    printf("%d ", (int) (sizeof(arr) / sizeof(arr[0])));
}

int main(void) {
    int a[10];
    f(a);
    printf("%d", (int) (sizeof(a) / sizeof(a[0])));
    return 0;
}
Show the answer and the worked solution

Correct answer: A.

2 10

Worked solution

  1. A parameter declared int arr[] is adjusted to int *arr, so inside f sizeof(arr) is the size of a pointer, 8 bytes, and sizeof(arr[0]) is 4.
  2. The division there gives 8 / 4 = 2.
  3. In main, a is a genuine array of 10 ints, so sizeof(a) is 40 and the division gives 40 / 4 = 10, making the output 2 10.

Answer: 2 10.

The idea

Arrays decay to pointers when passed to a function, which is exactly why C functions that take arrays also take a length. The sizeof trick works only in the scope where the array is declared.

Shortcut. Inside f the parameter is really int *, so the ratio is pointer size over int size, 8 ÷ 4 = 2; in main the true array gives 40 ÷ 4 = 10.

Common trap. "10 10" assumes the array keeps its size when passed; an array parameter decays to a pointer, so sizeof sees only 8 bytes.

sizeof on an array parameter — Aptitude Question

sizeof on an array parameter: Assume a machine where int occupies 4 bytes and a pointer occupies 8 bytes. Answer and worked solution on CodeKairo.

Question

Assume a machine where int occupies 4 bytes and a pointer occupies 8 bytes. What does this C program print?

#include <stdio.h>

void f(int arr[]) {
    printf("%d ", (int) (sizeof(arr) / sizeof(arr[0])));
}

int main(void) {
    int a[10];
    f(a);
    printf("%d", (int) (sizeof(a) / sizeof(a[0])));
    return 0;
}

Options

  1. 2 10
  2. 10 2
  3. 10 10
  4. 40 10
Show the answer and the worked solution

Correct answer: A. 2 10

Worked solution

  1. A parameter declared int arr[] is adjusted to int *arr, so inside f sizeof(arr) is the size of a pointer, 8 bytes, and sizeof(arr[0]) is 4.
  2. The division there gives 8 / 4 = 2.
  3. In main, a is a genuine array of 10 ints, so sizeof(a) is 40 and the division gives 40 / 4 = 10, making the output 2 10.

Answer: 2 10.

The idea

Arrays decay to pointers when passed to a function, which is exactly why C functions that take arrays also take a length. The sizeof trick works only in the scope where the array is declared.

Shortcut. Inside f the parameter is really int *, so the ratio is pointer size over int size, 8 ÷ 4 = 2; in main the true array gives 40 ÷ 4 = 10.

Common trap. "10 10" assumes the array keeps its size when passed; an array parameter decays to a pointer, so sizeof sees only 8 bytes.

All Programming Fundamentals questions · placement mock tests