CodeBlanks Logo Icon CodeBlanks

Array size

Learn to compute the array size with sizeof.

Array size with sizeof

C has no operator that directly gives array length. But sizeof tells you both the total bytes of the array and the bytes of one element; the division gives the length.

int scores[5] = {85, 92, 78, 90, 88};
int size = sizeof(scores) / sizeof(scores[0]);
printf("%d\n", size);  // 5

Here sizeof(scores) is 20 bytes (5 × 4), sizeof(scores[0]) is 4 bytes. The division gives 5. This idiom is useful for loop bounds.

sizeof as loop bound

Using the sizeof idiom for loop bounds is safer than hard-coding the size. If you change the size later, the loop adapts automatically.

int scores[5] = {85, 92, 78, 90, 88};
int n = sizeof(scores) / sizeof(scores[0]);
for (int i = 0; i < n; i++) {
    printf("%d\n", scores[i]);
}

This style makes maintenance easier. If the array grows to 10, the loop runs 10 times. Hard-coding 5 would risk forgetting the update.

Practice Print the array length

Write a C program. Declare int scores[5] = {85, 92, 78, 90, 88};. Compute the length with int n = sizeof(scores) / sizeof(scores[0]);. Print with printf("%d\n", n);. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare scores, compute length with sizeof and print it
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int scores[5] = {85, 92, 78, 90, 88};
    int n = sizeof(scores) / sizeof(scores[0]);
    printf("%d\n", n);
    return 0;
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the sizeof pieces

Term Meaning
sizeof(scores) Total bytes
sizeof(scores[0]) Single element bytes
sizeof(int) Type bytes
/ sizeof Division

2 How many bytes is sizeof(scores) for int scores[5]?

main.c
int scores[5];
sizeof(scores);
  • 4
  • 5
  • 10
  • 20 Correct answer

Explanation: 5 int × 4 bytes = 20.

3 Complete the length idiom

Question
int n = sizeof(scores) / sizeof(____);
Answer
int n = sizeof(scores) / sizeof(scores[0]);

Explanation: scores[0] gives the single element bytes.

All lessons in Beginner