Input an Array in C

Arrays in C store contiguous elements of identical type in physical RAM. Learn array declarations, O(1) index math, multi-dimensional layouts, and boundary protection.
Arrays are the most fundamental contiguous data structure in C. They group elements of identical type together in adjacent physical memory addresses, granting O(1) constant-time access via direct index offset math.
C uses zero-based indexing: an array int arr[5] has valid indices from 0 to 4. When an array name appears in most expressions, it automatically decays into a pointer to its first element (&arr[0]).
Because C prioritizes raw execution speed over defensive checks, the compiler never performs runtime array boundary validation. Reading or writing past an array boundary is a major cause of segmentation faults and security vulnerabilities.
Interactive Runnable C Implementation
#include <stdio.h>
#define MAX_SIZE 100
int main(void) {
int arr[MAX_SIZE];
int n;
int sum = 0;
printf("Enter number of elements (1 to %d): \n", MAX_SIZE);
if (scanf("%d", &n) != 1 || n <= 0 || n > MAX_SIZE) {
fprintf(stderr, "Error: Invalid number of elements.\n");
return 1;
}
printf("Reading %d integers from input...\n", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1) {
fprintf(stderr, "Error reading element at index %d.\n", i);
return 1;
}
sum += arr[i];
}
printf("\n--- Array Elements Summary ---\n");
for (int i = 0; i < n; i++) {
printf("arr[%d] = %d (Address: %p)\n", i, arr[i], (void *)&arr[i]);
}
double average = (double)sum / n;
printf("\nTotal Sum = %d\n", sum);
printf("Average = %.2f\n", average);
return 0;
}
Expected Output
Enter number of elements (1 to 100):
Reading 5 integers from input...
--- Array Elements Summary ---
arr[0] = 10 (Address: 0x...)
arr[1] = 25 (Address: 0x...)
arr[2] = 40 (Address: 0x...)
arr[3] = 55 (Address: 0x...)
arr[4] = 70 (Address: 0x...)
Total Sum = 200
Average = 40.00
Frequently Asked Questions
Why do we need the & (address-of) operator when reading into arr[i] with scanf?
arr[i] evaluates to the integer value at index i, but scanf requires a pointer (memory address) to write the input value directly into RAM.
Can array sizes be determined at runtime in modern C?
Variable Length Arrays (VLAs) are supported in C99, but dynamic memory allocation (malloc) is strongly preferred in production for safety and large buffers.