How do I determine the size of my array in C?

To determine the size of an array in C, you use the sizeof operator. However, there are nuances depending on the context (e.g., static arrays, dynamic arrays, arrays passed to functions). Below is a detailed explanation with examples for various scenarios.

1. Basic Method for Static Arrays

For arrays declared in the same scope where their size is needed:

Example 1: Integer Array

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50}; // Static array
    size_t num_elements = sizeof(arr) / sizeof(arr[0]);
    printf("Number of elements: %zu\n", num_elements); // Output: 5
    return 0;
}

Explanation:

  • sizeof(arr): Total bytes occupied by the array (e.g., 5 * sizeof(int) = 20 bytes if int is 4 bytes).
  • sizeof(arr[0]): Size of one element (e.g., 4 bytes for int).
  • Division: sizeof(arr) / sizeof(arr[0]) gives the number of elements.

2. Pitfall: Arrays Passed to Functions

When an array is passed to a function, it decays into a pointer, and sizeof returns the size of the pointer, not the array.

Example 2: Incorrect Size in Function

#include <stdio.h>

void printSize(int arr[]) {
    // This will NOT work! sizeof(arr) = size of a pointer (e.g., 8 bytes)
    size_t num_elements = sizeof(arr) / sizeof(arr[0]);
    printf("Incorrect size in function: %zu\n", num_elements);
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    printSize(arr); // Output: 2 (if pointer size is 8 bytes and int is 4 bytes)
    return 0;
}

Solution: Pass the size explicitly to the function:

void printSize(int arr[], size_t size) {
    for (size_t i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
}

int main() {
    int arr[] = {1, 2, 3};
    printSize(arr, sizeof(arr) / sizeof(arr[0])); // Pass size as argument
    return 0;
}

3. Dynamic Arrays (malloc/calloc)

For dynamically allocated arrays, sizeof returns the pointer size. You must track the size manually.

Example 3: Dynamic Array

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

int main() {
    size_t size = 5;
    int* dynamic_arr = malloc(size * sizeof(int));

    // sizeof(dynamic_arr) = size of a pointer (e.g., 8 bytes)
    printf("Pointer size: %zu\n", sizeof(dynamic_arr)); // Not the array size!

    free(dynamic_arr);
    return 0;
}

Best Practice:

size_t size = 5;
int* dynamic_arr = malloc(size * sizeof(int));

// Track the size manually!
for (size_t i = 0; i < size; i++) {
    dynamic_arr[i] = i;
}

4. Multidimensional Arrays

For multidimensional arrays, calculate rows and columns separately.

Example 4: 2D Array

#include <stdio.h>

int main() {
    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };

    size_t rows = sizeof(matrix) / sizeof(matrix[0]);       // 3 rows
    size_t cols = sizeof(matrix[0]) / sizeof(matrix[0][0]); // 4 columns

    printf("Rows: %zu, Columns: %zu\n", rows, cols);
    return 0;
}

5. Strings (Character Arrays)

For char arrays (strings), sizeof includes the null terminator (\0), while strlen does not.

Example 5: Char Array

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

int main() {
    char str[] = "Hello";
    size_t size_with_null = sizeof(str); // Includes '\0' (6 bytes)
    size_t length = strlen(str);         // Excludes '\0' (5)

    printf("Sizeof: %zu, strlen: %zu\n", size_with_null, length);
    return 0;
}

6. Variable-Length Arrays (VLAs)

For VLAs (C99+), sizeof works in the same scope.

Example 6: VLA

#include <stdio.h>

int main() {
    int n;
    printf("Enter array size: ");
    scanf("%d", &n);

    int vla[n];
    size_t num_elements = sizeof(vla) / sizeof(vla[0]);
    printf("VLA size: %zu\n", num_elements); // Correct if used in the same scope
    return 0;
}

7. Common Mistakes

Mistake 1: Using sizeof on a Pointer

int arr[] = {1, 2, 3};
int* ptr = arr;
printf("%zu\n", sizeof(ptr)); // Output: 8 (pointer size, not array size)

Mistake 2: Assuming sizeof Works in Functions

void func(int arr[5]) {
    printf("%zu\n", sizeof(arr)); // Output: 8 (pointer size)
}

Summary Table

ScenarioValid Use of sizeof?Solution
Static array in same scope✅ Yessizeof(arr) / sizeof(arr[0])
Array passed to function❌ NoPass size as a parameter
Dynamic array (malloc)❌ NoTrack size manually
Multidimensional array✅ YesCalculate rows/columns separately
Strings (char[])✅ Yes (with \0)Use strlen for length without \0

Key Takeaways

  • Use sizeof(arr) / sizeof(arr[0]) only in the scope where the array is declared.
  • For dynamic arrays or function parameters, track the size manually.
  • Avoid using sizeof on pointers (it returns the pointer size, not the array size).

Leave a Reply

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