C: Arrays

🗓 Last updated: 2026-11-30👤 Written by: Gray✓ Reviewed by: Dana🏷 Category: C Tutorial

Imagine a row of lockers, each numbered starting from 0, storing items of the same kind -- that is an array. It lets you manage a group of same-type data under one name.

Reference entries in this section: int for sizeof

1. Defining and Initializing One-Dimensional Arrays

An array is an ordered collection of elements of the same type, stored contiguously in memory. When defining an array, you specify the element type and the number of elements.

C
int scores[5];

This defines an array of 5 int elements, but the contents are uninitialized and the values are indeterminate. It is recommended to initialize the array at definition:

C
int scores[5] = {90, 85, 78, 92, 88};

If the initializer list is shorter than the array, the remaining elements are automatically set to 0:

C
int data[5] = {10, 20};

Now data[2], data[3], and data[4] are all 0. Using this property, you can zero out an entire array:

C
int zeros[100] = {0};

If you provide a complete initializer list, you can omit the array length and the compiler will calculate it automatically:

C
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

2. Subscript Access

Array elements are accessed by subscript (index), starting from 0. For an array of length N, the valid subscripts range from 0 to N-1.

C
int scores[5] = {90, 85, 78, 92, 88};

// Variable declaration
int first = scores[0];
// Variable declaration
int last = scores[4];

scores[2] = 100;

The subscript can be an integer expression, which makes loop traversal convenient:

TEXT
int i = 3;
int val = scores[i];
💡 Tip: Remember: for an array of length 5, the maximum subscript is 4, not 5. C does not check array bounds at runtime. Out-of-bounds access will not produce an error, but the consequences can be severe.


3. Out-of-Bounds Risks

C does not check whether array subscripts are out of bounds. Accessing out-of-bounds elements is undefined behavior -- it may read garbage data, modify other variables, or crash the program.

C
int arr[3] = {10, 20, 30};

// I/O operation
printf("%d\n", arr[3]);
// I/O operation
printf("%d\n", arr[-1]);

Both lines access illegal positions. The compiler will not warn you, but the results are unpredictable.

⚠️ Note: Out-of-bounds access is one of the most common bug sources in C. When writing loops, always verify boundary conditions and use < rather than <= when comparing against the length.


4. Array Traversal

Using a for loop to process each element sequentially is the most common array operation:

C
int scores[5] = {90, 85, 78, 92, 88};
// Variable declaration
int i;

// For loop
for (i = 0; i < 5; i++) {
    // I/O operation
    printf("scores[%d] = %d\n", i, scores[i]);
}

Sum all elements:

C
// Variable declaration
int sum = 0;
// For loop
for (i = 0; i < 5; i++) {
    sum += scores[i];
}
// I/O operation
printf("Total: %d\n", sum);

Find the maximum value:

TEXT
int max = scores[0];
for (i = 1; i < 5; i++) {
    if (scores[i] > max) {
        max = scores[i];
    }
}
printf("Highest: %d\n", max);

▶ Example

Calculate the average score and the number of failing grades:

▶ Try it Yourself
TEXT
Average: 73.5
Failing: 2

Here, sizeof(scores) / sizeof(scores[0]) dynamically calculates the number of elements, so you do not need to update the loop condition when changing the array contents.


5. Arrays as Function Parameters

When an array is passed to a function, the entire array is not copied -- only the address of the first element is passed. This means the function cannot determine the array length using sizeof; the length must be passed as a separate parameter.

C
// Function definition
void print_array(int arr[], int len) {
    // Variable declaration
    int i;
    // For loop
    for (i = 0; i < len; i++) {
        // I/O operation
        printf("%d ", arr[i]);
    }
    // I/O operation
    printf("\n");
}

The parameter int arr[] is equivalent to int *arr, which reflects the "decay" to a pointer. Modifying array elements inside the function affects the original array because both operate on the same memory.

C
// Function definition
void double_values(int arr[], int len) {
    // Variable declaration
    int i;
    // For loop
    for (i = 0; i < len; i++) {
        arr[i] *= 2;
    }
}

// Function definition
int main(void) {
    int data[] = {1, 2, 3, 4, 5};
    double_values(data, 5);
    // Return result
    return 0;
}

After the call, data contains {2, 4, 6, 8, 10}.


6. Two-Dimensional Arrays

A two-dimensional array can be thought of as an "array of arrays", commonly used to represent matrices or tabular data.

C
int matrix[3][4];

This defines a 3-row, 4-column two-dimensional array. Initialization can be grouped by row:

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

It can also be written flat -- the effect is the same:

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

Access elements using two subscripts:

C
// Variable declaration
int val = matrix[1][2];
matrix[0][0] = 100;

Traversing a two-dimensional array requires a double loop:

TEXT
int i, j;
for (i = 0; i < 3; i++) {
    for (j = 0; j < 4; j++) {
        printf("%4d", matrix[i][j]);
    }
    printf("\n");
}

When initializing, you can omit the row count but not the column count:

C
int m[][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8}
};

The compiler infers 2 rows from the initializer data.

▶ Example

Calculate the average score across 4 subjects for 3 students:

▶ Try it Yourself
TEXT
Student1 Average: 86.2
Student2 Average: 72.5
Student3 Average: 93.0
💡 Tip: When a two-dimensional array is used as a function parameter, the column count (second dimension size) must be specified; the row count is passed as a separate parameter.

▶ Example 3: Find Min and Max in an Array

▶ Try it Yourself

输出:

TEXT
Array: 34 7 23 32 5 62 4 19
Min = 4, Max = 62

Reference entries in this section: int for sizeof

❓ FAQ

Q What values are in an array that is defined but not initialized?
A Local arrays have indeterminate contents (garbage values on the stack); global and static arrays are automatically initialized to 0.
Q Why can't sizeof(arr) be used inside a function to find the element count?
A After an array is passed as a parameter, it decays to a pointer. sizeof gives the pointer size (4 or 8 bytes), not the total array size.
Q Can an array subscript be negative?
A Syntactically it compiles, but it accesses memory before the array's starting address, which is out-of-bounds and undefined behavior.
Q How are two-dimensional arrays stored in memory?
A In row-major order, contiguously. All elements of row 0 are stored first, then row 1, and so on.

📖 Summary

📝 Exercises

  1. Write a program that reads 10 integers into an array, then prints all elements in reverse order.
  2. Write a function that receives an integer array and its length, and returns the index of the maximum value.
  3. Define a 4x4 integer matrix, initialize it, and calculate the sum of both diagonals.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏