Reading history

sizeof Operator in C with Examples

6 min read 1 views

Learn the C sizeof operator: sizes of types, %zu, counting array elements, why arrays in functions become pointers, struct padding and malloc(n * sizeof *p).

The sizeof operator tells you how many bytes a type or an object occupies in memory. C programmers use it constantly: to count the elements in an array, to allocate the right amount of memory with malloc, and to write code that works on machines where an int or a pointer has a different size. It also has a few surprises, especially with arrays passed to functions. This lesson covers both.

In this lesson you will learn

  • Using sizeof on types and on expressions
  • Printing sizes with the %zu format
  • Counting array elements with sizeof a / sizeof a[0]
  • Why an array parameter is really a pointer
  • Safe allocation with malloc(n * sizeof *p)

You should know data types, arrays and pointers.

Sizes of Types and Arrays

#include <stdio.h>
#include <stdint.h>

int main(void) {
    /* sizeof gives a size in bytes, as a size_t: print it with %zu */
    printf("char %zu, short %zu, int %zu, long %zu, long long %zu\n",
           sizeof(char), sizeof(short), sizeof(int), sizeof(long), sizeof(long long));
    printf("float %zu, double %zu, pointer %zu\n",
           sizeof(float), sizeof(double), sizeof(void *));
    printf("int8_t %zu, int32_t %zu, int64_t %zu\n",
           sizeof(int8_t), sizeof(int32_t), sizeof(int64_t));

    int marks[10];
    double prices[4];
    printf("marks: %zu bytes, %zu elements\n", sizeof marks, sizeof marks / sizeof marks[0]);
    printf("prices: %zu bytes, %zu elements\n", sizeof prices, sizeof prices / sizeof *prices);

    /* sizeof works on expressions without evaluating them */
    int x = 5;
    size_t s = sizeof(x++);
    printf("sizeof(x++) = %zu, x is still %d\n", s, x);

    char name[] = "Dhaka";              /* 5 letters + the '\0' terminator */
    const char *p = "Dhaka";
    printf("sizeof name = %zu, sizeof p = %zu\n", sizeof name, sizeof p);
    return 0;
}

Output

char 1, short 2, int 4, long 8, long long 8
float 4, double 8, pointer 8
int8_t 1, int32_t 4, int64_t 8
marks: 40 bytes, 10 elements
prices: 32 bytes, 4 elements
sizeof(x++) = 4, x is still 5
sizeof name = 6, sizeof p = 8
  • sizeof(type) needs parentheses; sizeof object does not, though sizeof(object) works too.
  • The result has type size_t, an unsigned integer type, printed with %zu.
  • char is always 1 byte by definition. The other sizes shown are typical for 64-bit Linux and macOS; on 64-bit Windows long is 4 bytes. When you need an exact size, use the fixed-width types from <stdint.h> such as int32_t.
  • sizeof marks gives the size of the whole array (10 × 4 = 40 bytes). Dividing by the size of one element gives the element count, 10.
  • sizeof is worked out by the compiler and does not evaluate its operand. sizeof(x++) is 4, but x is not incremented.
  • char name[] = "Dhaka" is a 6-byte array because the string’s terminating '\0' is included. p is a pointer, so sizeof p is the size of a pointer, 8, whatever it points to.

Arrays in Functions, Structs and malloc

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student {
    char name[20];
    int roll;
    double cgpa;
};

/* Inside a function, an array parameter is really a pointer */
static void show_size(int arr[]) {
    printf("inside function: sizeof arr = %zu (size of a pointer)\n", sizeof(int *));
    (void)arr;
}

int main(void) {
    int data[8] = {0};
    printf("in main: sizeof data = %zu\n", sizeof data);
    show_size(data);

    printf("sizeof(struct student) = %zu\n", sizeof(struct student));

    /* Allocate with sizeof *ptr so the type is written only once */
    size_t n = 3;
    struct student *list = malloc(n * sizeof *list);
    if (list == NULL) return 1;
    memset(list, 0, n * sizeof *list);
    strcpy(list[0].name, "Nusrat");
    list[0].roll = 1;
    list[0].cgpa = 3.82;
    printf("allocated %zu bytes for %zu students; first: %s\n",
           n * sizeof *list, n, list[0].name);

    /* strlen counts characters; sizeof counts the whole array */
    char city[32] = "Sylhet";
    printf("strlen = %zu, sizeof = %zu\n", strlen(city), sizeof city);
    free(list);
    return 0;
}

Output

in main: sizeof data = 32
inside function: sizeof arr = 8 (size of a pointer)
sizeof(struct student) = 32
allocated 96 bytes for 3 students; first: Nusrat
strlen = 6, sizeof = 32
  • In main, data is an array of 8 ints, so sizeof data is 32. When it is passed to a function, it decays to a pointer, so inside the function only a pointer arrives. Writing sizeof arr there gives 8, the size of a pointer, and GCC warns about it. Always pass the element count as a separate parameter.
  • sizeof(struct student) is 32, more than the 20 + 4 + 8 bytes of its members would suggest. The compiler adds padding so the double starts at a suitably aligned address; see structure padding.
  • malloc(n * sizeof *list) asks for room for n students. Writing sizeof *list instead of sizeof(struct student) means the line stays correct if the pointer’s type changes later.
  • strlen counts the characters before '\0' (6 for “Sylhet”), while sizeof gives the full array size (32). They answer different questions.

sizeof Quick Reference

ExpressionGives
sizeof(int)Bytes in an int (usually 4)
sizeof arrBytes in the whole array (only where arr is a real array)
sizeof arr / sizeof arr[0]Number of elements
sizeof ptrBytes in a pointer (usually 8 on 64-bit systems)
sizeof *ptrBytes in the object the pointer points to
sizeof "abc"4, including '\0'
sizeof(struct s)Members plus any padding

Common Mistakes

  1. Using sizeof arr / sizeof arr[0] inside a function that received the array as a parameter.
  2. Printing a size_t with %d, which can print wrong values on 64-bit systems. Use %zu.
  3. Writing malloc(n * sizeof(ptr)), which allocates room for pointers instead of objects. Use sizeof *ptr.
  4. Assuming fixed sizes, such as a 4-byte long, in code that must run on several platforms.

Practice Exercises

Exercise 1. Write a macro COUNT(a) that gives the number of elements in an array.

Show answer
#define COUNT(a) (sizeof (a) / sizeof (a)[0])

int primes[] = {2, 3, 5, 7, 11};
printf("%zu\n", COUNT(primes));   /* 5 */

Use it only on real arrays, never on pointers.

Exercise 2. What does sizeof(char[10][3]) evaluate to?

Show answer

30. It is an array of 10 arrays of 3 chars, and each char is 1 byte.

Frequently Asked Questions

Is sizeof a function?

No. It is a compile-time operator (except for variable-length arrays). That is why it does not need parentheses around an expression and why it does not evaluate its operand.

Why is sizeof(‘A’) 4 in C?

In C, a character constant such as 'A' has type int, so its size is the size of an int. In C++ it has type char and the answer is 1.

Summary

  • sizeof gives a size in bytes as a size_t; print it with %zu.
  • sizeof a / sizeof a[0] counts elements of a real array only.
  • Arrays passed to functions become pointers; pass the length separately.
  • Allocate with malloc(n * sizeof *p).

Next: Reading Input Safely in C with fgets.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *