type arrayName[size];One-Dimensional Arrays in C: Declaration, Initialization, and Access
What is One-Dimensional Arrays in C? Core Concept & Direct Summary
How are 1D arrays declared, initialized using initializer lists, and manipulated in loops?
Of all the array shapes C supports, one-dimensional arrays do the heavy lifting. Real programs store lists constantly — test scores, prices, temperatures, player names, sensor readings — and a 1D array is the natural container for a single list of values.
The concept is simple enough (a row of boxes, numbered from zero), but there's real craft in the details: the different ways to declare and initialize, the difference between the size and the last index, how to safely compute an array's length, the input/output loops you'll write a thousand times. This tutorial covers all of it with the depth the pillar page couldn't fit — plus the memory picture that makes everything click.
(Suggested image: the hero graphic — a clean row of seven memory boxes labeled [0] through [6] holding values, with the single array name spanning them and the base address marked at the first box)
How Does One-Dimensional Arrays in C Work? In-Depth Mechanics & Architecture
Declaration: The Forms You Need to Know
The basic form:
Three rules for the size:
- It must be a positive integer. Zero or negative isn't allowed.
- It can be a constant expression — a literal (
5) or a#defined value: - In strict C, it can't be a runtime variable for a standard array… well, with one modern exception called a VLA (variable-length array), which C99 added:Practical advice: if the size must be flexible, declare a generous fixed maximum and track the actual count separately. VLAs are legal but discouraged in real code because a large user-supplied
ncan blow the stack.
⚠️ Uninitialized arrays contain garbage. If you declare int marks[5]; and read from it immediately, you get whatever bytes were lying around in memory. This is the same behavior we saw with auto variables in the storage classes tutorial — arrays don't get zeroed for free.
(Suggested image: two side-by-side boxes — "int marks[5]; → garbage, garbage, garbage, garbage, garbage" vs "int marks[5] = {0}; → 0, 0, 0, 0, 0")
Initialization: Every Form in One Place
This is where a lot of small confusions live, so here's the complete set.
Form 1: Full initialization with explicit size
Size 5, five values. Everything lines up.
Form 2: Size inferred from the values
Cleaner, and impossible to get the count wrong.
Form 3: Partial initialization — the rest become ZERO
This is genuinely useful, not just trivia — it's how the widely used zero-fill idiom works.
Form 4: The zero-fill idiom
One value supplied, the rest auto-filled with zeros. Memorize this one — you'll write it dozens of times.
Form 5: Initialize after declaring (element by element)
Verbose, but legitimate — and it's how you'd fill an array with computed values.
Form 6: Designated initializers (C99) — sparse assignment
When you only want to set some positions:
Handy for lookup tables with mostly-empty slots.
What you CANNOT do
To copy, you loop:
That's a real limitation C beginners from Python/JavaScript run into — and a genuine interview question.
(Suggested image: a comparison table graphic of all six initialization forms with their resulting arrays drawn out — very shareable and useful as a bookmark)
Accessing Elements: The Index Rules
The boundary rule, stated once and for all:
The declared number is the count, not the last index. int a[5] has five elements; the highest you may touch is a[4].
And C will not stop you from going out of bounds:
No runtime error. No warning (unless your compiler's static analysis happens to catch the literal case). Just wrong values and mysterious crashes. Array bounds discipline is entirely your responsibility in C — a fact that's responsible for a large share of real-world security vulnerabilities, from the gets() buffer overflow onward.
(Suggested image: the valid-index diagram with green boxes 0–4 and a red out-of-bounds arrow labeled "no checking, memory corruption risk")
Getting the Size: The sizeof Idiom
Hard-coding 5 in your loops works until the array changes size. The robust pattern:
sizeof(marks)— the array's total size in bytessizeof(marks[0])— one element's size in bytes- Divide → element count
Important caveat: this only works where the array is a real array — in the same scope where it was declared. Once you pass an array to a function, it decays to a pointer and sizeof gives the pointer's size (usually 8), not the array's. That's why array functions need the count passed separately — a detail we'll explore fully in the "Passing Arrays to Functions" tutorial.
(Suggested image: the sizeof division shown as a literal calculation over a memory diagram)
Input and Output: The Loops You'll Write Forever
Reading values into an array:
Printing an array:
That & distinction is worth pausing on: scanf needs the address of the element (&marks[i]) to write into it, while printf just needs the value (marks[i]). Same "& means address" rule from our scanf tutorial, applied per-element.
The Name-Only Print: A Fun Trap
Printing marks with %d won't give you the whole array — C has no built-in "print entire array" feature. That's exactly why loops exist. (For char arrays, %sdoes work — because strings are special — but that's the Strings cluster.)
Memory Layout, Revisited (The Part That Unlocks Pointers)
Two facts to carry forward:
1. Element address = base + (index × size).nums[2] = 1000 + (2 × 4) = 1008. Direct arithmetic, which is why nums[i] is O(1) no matter how big the array.
2. The array name is the address of element 0.nums ≡ &nums[0]. This is why:
- You pass arrays to functions by writing just
func(nums)(no&needed — it's already an address) printf("%p", nums)prints the base address- Array indexing and pointer arithmetic are two views of the same thing
You'll see *(nums + i) written instead of nums[i] in older and lower-level code — identical in meaning. That's a pointers-cluster topic, but now you can see why it works.
(Suggested image: the address diagram with the formula base + i × size annotated — keep it consistent with the pillar page's version for visual continuity)
Core Example Set: The Five Patterns Everyone Needs
1. Sum and average
2. Largest and smallest
Starting from arr[0] rather than 0 (or some huge sentinel) is the robust choice — it works for any data, including all-negative arrays where a 0 start would fail.
3. Reverse the array in place
Two indexes meeting in the middle — swap until they cross. This is the classic in-place reversal, and the two-variable for header (from our for-loop tutorial) makes it compact.
4. Copy an array
5. Count occurrences / search linearly
(Suggested image: mini-diagrams for each pattern — especially the two-pointer reversal, which is a favorite exam/programming question)
A Complete Example: A Temperature Analyzer
Sample Run:
This one program exercises the whole page: fixed-size declaration with #define, array input with &, single-pass statistics starting from element 0, tracking which index holds the extreme values, and multi-way output logic combining the if-else and printf-formatting skills from earlier clusters. That's what real array code looks like.
Common 1D Array Mistakes
- Off-by-one in loops —
i <= nreads/writes a nonexistent element.i < n, always. - Confusing size with last index —
int a[5]→ last index 4. - Assuming zeroed memory — uninitialized arrays hold garbage. Use
= {0}. b = afor copying — illegal for arrays; loop instead.- Comparing with
==— compares addresses, not contents. - Using
sizeofafter passing to a function — gives the pointer size, not the array size. Pass the count explicitly. - Variable-length arrays with user input and no validation —
int a[n]wherenis 10 million can overflow the stack. Prefer#definemaxima. - Using
%son a non-char array — reads past the array looking for a null terminator, with predictably bad results.
(Suggested image: "8 Array Mistakes" checklist graphic — consistent with the series)
Final Thoughts
One-dimensional arrays are the plainest data structure in C — a row of same-typed boxes, numbered from zero — and somehow they still do most of the work in real programs. Master the declaration and initialization forms, internalize the boundary rule, get comfortable with the input/analyze/report loop pattern, and you've got a tool you'll use in literally every project from here on.
The two facts to keep closest: the size is a count, not an index, and C will not catch you going out of bounds. Everything else is practice.
Next in this cluster: two-dimensional arrays — where a single index becomes row and column, and grids and matrices open up.
Runnable C Code Example & Practical Implementation
#include <stdio.h>
int main() {
int values[] = {
10, 20, 30, 40, 50
};
int size = sizeof(values) / sizeof(values[0]);
int sum = 0;
for (int i = 0; i < size; i++) {
sum += values[i];
}
printf("Sum of array elements: %d (Average: %.1f)\
", sum,(double)sum / size);
return 0;
}Key Takeaways, Best Practices & Memory Safety Rules
memset(arr, 0, sizeof(arr)); or {0} initialization to clear arrays cleanly before use.Frequently Asked Questions & Technical Interview Insights
Technical Interview & Viva Questions
Frequently asked C programming interview questionsQ: What is the effect of `int arr[100] = {0};`?
Q: Can you assign one array directly to another (`arr1 = arr2;`) in C?
Related Tools, Tutorials & Authoritative References
Recommended Interactive Tools
- Online C Compiler & Runner — Interactive online GCC sandbox to execute C code in real time.
- Online C Code Editor & IDE — Multi-file C programming environment with code formatting.
- C++ Programming Tutorial — Transition from procedural C to Object-Oriented C++ with STL.
- JavaScript Programming Tutorial — Master modern JavaScript fundamentals, DOM APIs, and async patterns.
Authoritative Standards & Citations
- ISO/IEC 9899 (C Language Standard) — Official international C specification by ISO/IEC JTC 1/SC 22/WG 14.
- GNU GCC Documentation — Official reference manual for the GNU Compiler Collection and C libraries.
- The C Programming Language (K&R) — Definitive classic work by Brian Kernighan & Dennis Ritchie at Bell Labs.
- C Reference Documentation (cppreference.com) — Verified reference covering C89 through C23 language features.