0
0
Cprogramming~5 mins

Array size and bounds in C

Choose your learning style9 modes available
Introduction

Arrays hold many values in one place. Knowing their size and limits helps avoid errors.

When you want to store a fixed number of items like scores or names.
When you need to loop through all items safely without going outside the array.
When you want to check if an index is valid before accessing an array element.
Syntax
C
/* Define an array with a fixed size */
int numbers[5];

/* Access elements from 0 to size-1 */
numbers[0] = 10;
numbers[4] = 50;

/* Accessing outside bounds causes errors */
// numbers[5] = 60; // WRONG! Index 5 is out of bounds

Array indexes start at 0 and go up to size-1.

Accessing outside these bounds causes undefined behavior and bugs.

Examples
An array with zero size has no elements. Accessing any index is invalid.
C
int empty_array[0];
// This array has size 0, no elements to access.
An array with one element can only be accessed at index 0.
C
int single_element[1];
single_element[0] = 100;
// Only index 0 is valid here.
Accessing index equal to the size (3) is out of bounds.
C
int fruits[3] = {10, 20, 30};
// Valid indexes: 0, 1, 2
// fruits[3] is invalid and causes errors.
Sample Program

This program shows how to find the size of an array and safely access its elements using a loop.

C
#include <stdio.h>

int main() {
    int scores[4] = {85, 90, 78, 92};
    int size = sizeof(scores) / sizeof(scores[0]);

    printf("Array size: %d\n", size);

    printf("Scores: ");
    for (int index = 0; index < size; index++) {
        printf("%d ", scores[index]);
    }
    printf("\n");

    // Trying to access out of bounds (commented out to avoid crash)
    // printf("%d", scores[4]); // Invalid access

    return 0;
}
OutputSuccess
Important Notes

Time complexity to access an element is O(1).

Always use the array size to avoid going out of bounds.

Common mistake: Accessing index equal or greater than size causes crashes or bugs.

Use loops with size checks to safely process arrays.

Summary

Arrays have a fixed size known at compile time.

Valid indexes are from 0 to size-1.

Accessing outside these bounds causes errors and must be avoided.