1. What is an Array?¶
In C++, an array is a collection of elements of the same type, stored contiguously in memory. Once defined, the size of an array is fixed (static array), and each element is accessed through an index (starting from 0). For example, an array storing 5 integers has indices ranging from 0 to 4, with each element of type int.
2. Array Initialization Methods¶
Initialization means assigning values to array elements. A common question for beginners is “How to correctly assign values to an array?” Initialization methods vary slightly depending on the scenario.
1. Basic Type Arrays (e.g., int, double)¶
(1) Full Initialization (All elements are assigned)¶
Directly list all elements using curly braces {}, with the number of elements equal to the array size:
// Define an int array of size 5 and assign all elements
int arr[5] = {10, 20, 30, 40, 50};
// Note: The number of elements must equal the array size, otherwise an error occurs
// int arr[3] = {1,2,3,4}; // Error! Number of elements exceeds array size
(2) Partial Initialization (Only some elements are assigned)¶
If only some elements are assigned, unexplicitly assigned elements are automatically initialized to 0 (default value for basic types):
// Define an array of size 5, only the first 3 elements are assigned, the last 2 are automatically 0
int arr[5] = {1, 2, 3};
// The elements of arr are: arr[0]=1, arr[1]=2, arr[2]=3, arr[3]=0, arr[4]=0
(3) Omit Array Size, Let Compiler Derive Automatically¶
If the number of elements is known, the array size can be omitted, and the compiler automatically determines the size based on the number of initialized elements:
int arr[] = {1, 2, 3, 4, 5}; // Compiler automatically derives arr size as 5
cout << "Array size: " << sizeof(arr)/sizeof(arr[0]) << endl; // Outputs 5
2. Character Arrays (char)¶
Character arrays store characters and require special handling for strings (terminated by '\0').
(1) Initialize with String Literal (Automatically add '\0')¶
Directly use double quotes "" to enclose a string, and the compiler automatically appends the null character '\0' (string termination flag):
char str1[] = "hello"; // Equivalent to {'h','e','l','l','o','\0'}
// Note: The string length is 5 (excluding '\0'), and the array size is 6 (including '\0')
(2) Initialize with Individual Characters (Manually handle '\0')¶
If manually specifying the array size, ensure the string is terminated by '\0', otherwise it may not represent a valid string:
char str2[6] = {'h', 'e', 'l', 'l', 'o', '\0'}; // Manually add '\0'
char str3[5] = {'a', 'b', 'c'}; // No '\0' added; array elements are {'a','b','c',0,0} (0 is default)
3. Array Traversal Techniques¶
Traversal means accessing each element in order, typically implemented with loops.
1. Ordinary for Loop (Most Common, Requires Known Array Size)¶
Use index i to traverse from 0 to size-1 (for an array of size n, indices range from 0 to n-1):
int arr[] = {10, 20, 30, 40};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate array size (critical!)
// Traverse and print each element
for (int i = 0; i < n; i++) {
cout << "arr[" << i << "] = " << arr[i] << endl;
}
2. Range-based for Loop (C++11 New, No Index Needed)¶
Use for (auto element : arr) to directly traverse all elements, suitable for scenarios where indices are not needed:
int arr[] = {1, 2, 3, 4, 5};
for (auto num : arr) { // auto automatically deduces element type (int)
cout << num << " ";
}
cout << endl; // Output: 1 2 3 4 5
Note: The range-based for loop cannot access indices (use ordinary for if indices are needed). Modifying element does not change the original array (use references for modification: for (auto &num : arr)).
3. Special Notes on Character Array Traversal¶
A character array can be treated as a string, but the '\0' termination character must be noted:
char str[] = "hello";
// Traverse the string (judge end with '\0')
for (int i = 0; str[i] != '\0'; i++) {
cout << str[i]; // Output: hello
}
4. Important Notes¶
- Array Out-of-Bounds: Indices must be between
0andn-1(wherenis the array size). Out-of-bounds accesses unknown memory, causing crashes or data errors:
int arr[3] = {1,2,3};
arr[3]; // Out-of-bounds! Index 3 exceeds array size (max index 2), error!
-
Fixed Array Size: The size cannot be dynamically expanded after definition. For example,
int arr[5]cannot be directly resized toarr[6]; redefine the array instead. -
Character Array ≠ String: Only character arrays terminated by
'\0'can be processed with string functions (e.g.,strlen); otherwise, truncation may occur.
Summary¶
Arrays are fundamental structures for storing homogeneous data in C++. Key points:
- Initialization: Choose full/partial initialization based on needs. For character arrays, ensure '\0' termination.
- Traversal: Use ordinary for loop (needs indices) or range-based for loop (no indices). Avoid out-of-bounds access.
- Critical Operations: Get array size via sizeof(arr)/sizeof(arr[0]). Static arrays cannot change size dynamically.
Practice different initialization and traversal scenarios to master array usage!