When storing a list of related values—like daily temperatures or exam scores—the array in C++ is the simplest structure to use. A one-dimensional (1D) array is a fixed-size list of elements of the same type that are stored in contiguous memory. For beginners, learning 1D arrays is a crucial step toward mastering data handling in C++.
🔹 What is a 1D Array in C++?
A 1D array is a linear collection of values of the same type.
Each value is accessed via a zero-based index using square brackets []
.
Analogy: Picture a row of lockers labeled 0 to N-1. The row is the array, and each locker is an element identifiable by its index (label).
1. Declaring and Initializing 1D Arrays (Different Ways)
There are many valid ways to initialize a 1D array in C++. Below are the most common patterns with examples.
Method A: Explicit size with full initializer
#include <iostream>
int main() {
int scores[5] = {94, 88, 72, 98, 81}; // size and all values
std::cout << "scores[3] = " << scores[3] << std::endl; // 98
return 0;
}
📝 Try it Yourself: Change one element and print the whole array using a loop.
Method B: Size deduced from initializer
#include <iostream>
int main() {
double prices[] = {19.99, 25.50, 9.75}; // compiler deduces size = 3
std::cout << "Second price = " << prices[1] << std::endl; // 25.5
return 0;
}
📝 Try it Yourself: Add one more price and print the updated size using
sizeof(prices)/sizeof(prices[0])
.
Method C: Zero-initialize all elements
Using either {}
or {0}
zero-initializes the whole array.
#include <iostream>
int main() {
int data1[5] = {}; // all zeros
int data2[5] = {0}; // all zeros
std::cout << data1[0] << " " << data2[0] << std::endl; // 0 0
return 0;
}
📝 Try it Yourself: Verify all elements are zero by printing them in a loop.
Method D: Partial initialization (rest become zero)
Values not listed are automatically initialized to zero (for static and aggregate initialization).
#include <iostream>
int main() {
int nums[5] = {1, 2}; // becomes {1, 2, 0, 0, 0}
std::cout << nums[2] << " " << nums[4] << std::endl; // 0 0
return 0;
}
📝 Try it Yourself: Initialize the first three elements and check the last two.
Method E: Default-initialized local array (uninitialized values!)
Declaring a local array without an initializer leaves elements uninitialized (indeterminate values). Avoid reading before writing.
int main() {
int a[3]; // uninitialized; values are indeterminate
a[0] = 10;
a[1] = 20;
a[2] = 30;
}
📝 Try it Yourself: Try printing before assigning and observe why you shouldn’t rely on default values.
Method F: Initialize after declaration (loop)
#include <iostream>
int main() {
int multiples[5];
for (int i = 0; i < 5; ++i) {
multiples[i] = (i + 1) * 10; // 10, 20, 30, 40, 50
}
}
📝 Try it Yourself: Fill an array with squares: 1, 4, 9, 16, 25.
Method G: Initialize using algorithms (std::fill
)
Use standard algorithms to set all values to the same number quickly.
#include <algorithm>
#include <iostream>
int main() {
int arr[6];
std::fill(std::begin(arr), std::end(arr), 42); // all elements = 42
}
📝 Try it Yourself: Combine
std::iota
(from <numeric>) to fill with 1..N.
Method H: Character arrays from string literal
String literals automatically include a null terminator '\0'
.
#include <iostream>
int main() {
char word[] = "hello"; // size is 6: 'h','e','l','l','o','\0'
std::cout << word << std::endl;
}
📝 Try it Yourself: Create
char w[] = {'O','K','\\0'}
and print it.
2. Iterating and Using 1D Arrays
Use a loop to process all elements. Remember that array bounds are fixed and indices start at 0.
int main() {
int a[] = {3, 1, 4, 1, 5};
int n = sizeof(a)/sizeof(a[0]);
for (int i = 0; i < n; ++i) {
// process a[i]
}
}
3. Common Tips and Pitfalls
- Array size is fixed at compile time; use
std::vector
for dynamic sizes. - Never access out-of-bounds indices—it’s undefined behavior.
- Use
sizeof(a)/sizeof(a[0])
only in the same scope where the array is declared (not after decay to pointer).
🔹 Frequently Asked Questions (FAQ)
Q: Can I change the size of an array after creation?
A: No. For resizable containers, use std::vector
.
Q: Why is the first index 0?
A: It reflects the offset from the array’s starting memory address.
Q: How do I set all elements to a value?
A: Use a loop or std::fill
.
Q: Is int a[n]
valid if n
is not a constant?
A: Standard C++ requires compile-time constant bounds.
Variable-length arrays are not standard (they are a compiler extension in some environments).