C•Arrays
C Arrays: Contiguous Stack Buffers and Multi-Dimensional Arrays
Arrays in C store elements of the same type sequentially in memory, decaying to pointers when passed to functions.
Syntax
int numbers[5] = {1, 2, 3, 4, 5};
int val = numbers[0];
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| numbers[N] | Stack Buffer | Allocates N * sizeof(type) bytes on stack. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C locally:
#include <stdio.h>
int main(void) {
int metrics[] = {120, 240, 360, 480};
int length = sizeof(metrics) / sizeof(metrics[0]);
printf("Total elements: %d\n", length);
printf("Total bytes: %zu\n", sizeof(metrics));
// Access by index
printf("First metric: %d\n", metrics[0]);
printf("Last metric: %d\n", metrics[length - 1]);
// Mutate in place
metrics[1] = 999;
printf("Modified index 1: %d\n", metrics[1]);
return 0;
}Expected Output:
Total elements: 4 Total bytes: 16 First metric: 120 Last metric: 480 Modified index 1: 999
How It Works: Step-by-Step
- Lines 4-5: Initializes array and calculates element count using sizeof.
- Lines 10-11: Accesses elements using zero-based indexing.
- Line 14: Modifies element in-place.
Key Concepts
- In C, array bounds are NOT checked at runtime; accessing out of bounds causes memory corruption.
- Array names decay to a pointer to their first element when passed into functions.
Common Mistake: Using sizeof(arr) inside a function receiving an array parameter
Inside functions, array parameters decay to pointers; sizeof(arr) returns pointer size (8 bytes), not array size.
❌ Incorrect
void print(int arr[]) {
int len = sizeof(arr)/sizeof(arr[0]); // Bug: len is 8/4 = 2!
}✅ Correct
void print(int arr[], int len) { /* Always pass length explicitly */ }Related C Tutorials & Compiler
C Structs: Grouping Heterogeneous Data Records
Define compound records in C using struct and typedef struct.
C Strings: Null-Terminated Character Arrays (char[])
Master null-terminated strings (\0), strlen, strcpy, strcat, and strcmp from string.h.
C Pointers: Memory Addresses, Dereferencing (*), and Pointer Arithmetic
Master pointers in C: address-of (&), dereferencing (*), pass-by-reference simulation, and pointer math.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.