🧠 What Is an Array?
Imagine you are a teacher with 100 students. You want to store each student’s marks.
If you use separate variables:
int mark1, mark2, mark3, ..., mark100;😩 That’s exhausting, error-prone, and not practical.
✅ Instead, an array lets you store all 100 marks in a single variable name, like:
int marks[100];🔁 So, an array is like a row of lockers 📦 — each box (element) holds a value and has a unique number (index).
📚 Simple Definition
An array in C is a collection of fixed-size elements of the same data type, stored in continuous memory locations, and accessed using an index.
<div class="infographic-carray">
<style>
.infographic-carray {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--code-bg: #1e1e2e;
--code-text: #d4d4e0;
--syn-keyword: #c586c0;
--syn-func: #dcdcaa;
--syn-comment: #6a9955;
--warn: #b45309;
--warn-soft: #fdf0dc;
}
.infographic-carray[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--code-bg: #0d0d14;
--code-text: #d4d4e0;
--warn: #e0a458;
--warn-soft: #3a2c14;
}
.infographic-carray {
box-sizing: border-box;
max-width: 760px;
margin: 0 auto;
background: var(--paper);
color: var(--ink);
font-family: 'Inter', -apple-system, sans-serif;
padding: 0 clamp(1rem, 4vw, 2.25rem) 1.25rem;
}
.infographic-carray *, .infographic-carray *::before, .infographic-carray *::after {
box-sizing: border-box;
}
.infographic-carray h1 {
font-family: 'Fraunces', Georgia, serif;
font-weight: 600;
font-size: clamp(1.4rem, 3.5vw, 1.9rem);
margin: 1.25rem 0 0.25rem;
}
.infographic-carray .subhead { color: var(--ink-soft); font-size: 0.85rem; margin-bottom: 1rem; }
.infographic-carray .code-panel {
background: var(--code-bg);
color: var(--code-text);
border-radius: 8px;
padding: 0.7rem 0.9rem;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.82rem;
line-height: 1.6;
margin-bottom: 0.9rem;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
max-width: 100%;
}
.infographic-carray .syn-keyword { color: var(--syn-keyword); }
.infographic-carray .syn-func { color: var(--syn-func); }
.infographic-carray .syn-comment { color: var(--syn-comment); }
.infographic-carray .field-row { display: flex; align-items: center; gap: 0.6rem; flex-wrap: wrap; margin-bottom: 1rem; }
.infographic-carray .field-row label { font-size: 0.82rem; color: var(--ink-soft); }
.infographic-carray .field-row input {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.88rem;
padding: 0.35rem 0.55rem;
border-radius: 6px;
border: 1px solid var(--line);
background: var(--paper);
color: var(--ink);
}
.infographic-carray #arr-values-input { width: 15rem; max-width: 100%; }
.infographic-carray #arr-index-input { width: 4.5rem; }
.infographic-carray .field-row input:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
.infographic-carray .array-row {
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
margin-bottom: 0.35rem;
}
.infographic-carray .cell {
cursor: pointer;
min-width: 3.2rem;
text-align: center;
border: 1px solid var(--line);
border-radius: 8px;
padding: 0.5rem 0.3rem 0.4rem;
background: var(--paper-alt);
transition: border-color 0.2s, background 0.2s, transform 0.15s;
}
.infographic-carray .cell:hover { transform: translateY(-2px); }
.infographic-carray .cell .idx {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.68rem;
color: var(--ink-soft);
margin-bottom: 0.15rem;
}
.infographic-carray .cell .val {
font-family: 'IBM Plex Mono', monospace;
font-size: 1rem;
font-weight: 700;
color: var(--ink);
}
.infographic-carray .cell.is-selected {
border-color: var(--accent);
background: var(--accent-soft);
box-shadow: 0 3px 10px -4px rgba(0,0,0,0.25);
}
.infographic-carray .cell.is-selected .idx,
.infographic-carray .cell.is-selected .val { color: var(--accent); }
.infographic-carray .facts { font-size: 0.78rem; color: var(--ink-soft); margin-bottom: 1rem; }
.infographic-carray .result-panel {
padding: 0.75rem 1rem;
background: var(--paper-alt);
border-radius: 8px;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.85rem;
color: var(--ink);
min-height: 2.4rem;
}
.infographic-carray .result-panel.is-warn {
background: var(--warn-soft);
color: var(--warn);
font-family: 'Inter', sans-serif;
font-weight: 600;
}
.infographic-carray .takeaway { font-size: 0.82rem; color: var(--ink-soft); margin-top: 1.25rem; border-top: 1px solid var(--line); padding-top: 0.9rem; }
.infographic-carray .takeaway strong { color: var(--ink); }
@media (prefers-reduced-motion: reduce) {
.infographic-carray * { transition: none !important; }
}
</style>
<h1>🧱 Arrays in C</h1>
<p class="subhead">Edit the array, then look up any index — including ones that don't exist.</p>
<div class="code-panel"><span id="arr-code"></span></div>
<div class="field-row">
<label>Array values:</label>
<input type="text" id="arr-values-input" value="10, 20, 30, 40, 50">
</div>
<div class="array-row" id="arr-cells"></div>
<p class="facts" id="arr-facts"></p>
<div class="field-row">
<label>arr[ <input type="number" id="arr-index-input" value="0"> ]</label>
</div>
<div class="result-panel" id="arr-result"></div>
<p class="takeaway"><strong>The rule:</strong> valid indices run from <code style="font-family:'IBM Plex Mono',monospace;">0</code> to <code style="font-family:'IBM Plex Mono',monospace;">size - 1</code>. C won't stop you from going outside that range — it just reads whatever memory happens to be there.</p>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-carray')
|| document.querySelector('.infographic-carray');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') { dark = true; }
else if (bodyAttr === 'false') { dark = false; }
else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
function $(sel) { return wrapper.querySelector(sel); }
const valuesInput = $('#arr-values-input');
const indexInput = $('#arr-index-input');
const cellsRow = $('#arr-cells');
const codeEl = $('#arr-code');
const factsEl = $('#arr-facts');
const resultEl = $('#arr-result');
const BASE_ADDR = 0x7ffe1000;
let arr = [];
function parseValues() {
arr = valuesInput.value.split(',')
.map(s => s.trim())
.filter(s => s.length > 0)
.map(s => {
const n = parseInt(s, 10);
return isNaN(n) ? 0 : n;
});
if (arr.length === 0) arr = [0];
}
function renderCode() {
codeEl.innerHTML = '<span class="syn-keyword">int</span> <span class="syn-func">arr</span>[' + arr.length + '] = {' + arr.join(', ') + '};';
}
function renderCells() {
cellsRow.innerHTML = '';
arr.forEach((v, i) => {
const cell = document.createElement('div');
cell.className = 'cell';
cell.dataset.index = i;
cell.innerHTML = '<div class="idx">' + i + '</div><div class="val">' + v + '</div>';
cell.addEventListener('click', () => {
indexInput.value = i;
showLookup();
});
cellsRow.appendChild(cell);
});
}
function renderFacts() {
factsEl.textContent = 'arr has ' + arr.length + ' elements — valid indices are 0 to ' + (arr.length - 1) +
'. sizeof(arr) = ' + (arr.length * 4) + ' bytes (int = 4 bytes × ' + arr.length + ').';
}
function showLookup() {
const i = parseInt(indexInput.value, 10);
wrapper.querySelectorAll('.cell').forEach(c => c.classList.remove('is-selected'));
if (isNaN(i)) {
resultEl.className = 'result-panel';
resultEl.textContent = '';
return;
}
if (i >= 0 && i < arr.length) {
const cell = cellsRow.querySelector('[data-index="' + i + '"]');
if (cell) cell.classList.add('is-selected');
const addr = (BASE_ADDR + i * 4).toString(16);
resultEl.className = 'result-panel';
resultEl.textContent = 'arr[' + i + '] = ' + arr[i] + ' (address 0x' + addr + ')';
} else {
resultEl.className = 'result-panel is-warn';
resultEl.textContent = '⚠️ arr[' + i + '] is out of bounds — C won\u2019t stop you, but the value is undefined (garbage or a crash).';
}
}
function rebuildAll() {
parseValues();
renderCode();
renderCells();
renderFacts();
showLookup();
}
valuesInput.addEventListener('input', rebuildAll);
indexInput.addEventListener('input', showLookup);
rebuildAll();
})();
</script>🗃️ Real-Life Analogy: “Mailboxes”
📬 Suppose your apartment has 5 mailboxes:
Each mailbox is labeled 0 to 4 (just like array indexes).
All mailboxes store letters (same type).
You can access a specific one using its number (index).
Same way:
int boxes[5]; // 5 boxes, for integer letters📌 Key Points About Arrays
🔎 Point | ✅ Description |
|---|---|
🎯 Fixed Size | Once declared, size can't change |
🧱 Same Type | All elements must be of same type (e.g., |
🧮 Indexed | Index starts from 0 |
🔗 Continuous | Stored in continuous memory blocks |
⛔ No Resize | C arrays don't grow/shrink dynamically |
🛠️ Syntax of Array Declaration
data_type array_name[size];💡 Examples:
int numbers[5]; // Integer array of size 5
float prices[10]; // Float array of 10 elements
char letters[26]; // Character array for A-Z🧾 How Memory Works Internally
Let’s say:
int arr[3] = {10, 20, 30};This means:
Index | Value | Memory Address (Example) |
|---|---|---|
0 | 10 | 1000 |
1 | 20 | 1004 |
2 | 30 | 1008 |
(Assuming each int is 4 bytes)
✅ Arrays are stored back-to-back in memory, which makes accessing elements very fast.
🧩 Why Use Arrays?
Without Array:
int a = 5, b = 10, c = 15;With Array:
int numbers[3] = {5, 10, 15};Now you can do:
for(int i = 0; i < 3; i++) {
printf("%d ", numbers[i]);
}✔️ Less Code
✔️ Loop-Friendly
✔️ Scalable to 1000+ elements
✔️ Easy to pass to functions
🔄 Accessing Array Elements
You can access or modify array values using index:
numbers[0] = 25; // Changes first element
printf("%d", numbers[2]); // Prints third element⚠️ Array indexes start from 0. So arr[5] in an array of size 5 is invalid!
🔍 Default Values in Arrays
If you don’t initialize:
int x[3]; // x may contain garbage valuesIf you partially initialize:
int x[5] = {1, 2}; // Rest become 0 → {1, 2, 0, 0, 0}🧪 Example: Student Marks
#include <stdio.h>
int main() {
int marks[5]; // stores marks of 5 students
for(int i = 0; i < 5; i++) {
printf("Enter mark %d: ", i + 1);
scanf("%d", &marks[i]);
}
printf("Entered marks:\\n");
for(int i = 0; i < 5; i++) {
printf("marks[%d] = %d\\n", i, marks[i]);
}
return 0;
}Enter mark 1: 80
Enter mark 2: 60
Enter mark 3: 40
Enter mark 4: 95
Enter mark 5: 75
Entered marks:
marks[0] = 80
marks[1] = 60
marks[2] = 40
marks[3] = 95
marks[4] = 75❌ Common Mistakes
Mistake | Explanation |
|---|---|
Accessing out of bounds like | Causes undefined behavior |
Using different data types | Not allowed |
Forgetting to initialize | May hold garbage |
💡 Array vs Variable Comparison
Feature | Variable | Array |
|---|---|---|
Storage | One value | Many values |
Access | Direct | By index |
Memory | One block | Continuous blocks |
Syntax |
|
|
How to check the length of arrays in C??
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);
printf("Length of array = %d\\n", length);
return 0;
}Length of array = 5