<Definition, Reference, and Initialization of One-Dimensional Arrays>From novice to expert, from Hello World to ACMAll practical content, no textbooks required!
<Lecture>
1. Concept of Arrays and Memory Allocation
1.1 What is an Array?
Basic Concept of Arrays: An array is a collection of data of the same type, stored contiguously in memory, where each data element is called an array element and accessed via an index.
Why Do We Need Arrays?
Imagine if we need to store the scores of 100 students; using ordinary variables would require declaring 100 different variable names, which is nearly impossible. With arrays, we only need one variable name to manage all the data.
Characteristics of Arrays:
-
All elements have the same data type
-
Elements are stored contiguously in memory
-
Elements are accessed via an index (starting from 0)
-
The length of the array is fixed after definition
1.2 Memory Allocation Principles of Arrays
Memory Model Example:
int scores[5]; // Declare an array containing 5 integers
Memory Layout:
Address: 1000 1004 1008 1012 1016
Element: scores[0] scores[1] scores[2] scores[3] scores[4]
Value: ? ? ? ? ?
Characteristics of Memory Allocation:
-
Each int type occupies 4 bytes (may vary by system)
-
Array elements are stored contiguously in memory
-
The array name represents the address of the first element
-
Any element can be accessed via address offset
Common Pitfalls
Array Out-of-Bounds Access: This is the most common error; accessing a non-existent array element can lead to undefined behavior.
int arr[5] = {1, 2, 3, 4, 5};
printf("%d", arr[5]); // Error! Valid indices are 0-4, arr[5] is out of bounds
2. Definition and Initialization of One-Dimensional Arrays
2.1 Definition of One-Dimensional Arrays
Basic Syntax:
DataType ArrayName[ArrayLength];
Definition Examples:
// Define different types of arrays
int numbers[10]; // Integer array, containing 10 elements
float temperatures[7]; // Float array, containing 7 elements
char letters[26]; // Character array, containing 26 elements
Array Definition Rules:
-
The array length must be an integer constant or constant expression
-
The array length cannot be changed after definition
-
The array name must comply with identifier naming rules
2.2 Initialization of One-Dimensional Arrays
Initialization Methods:
// Method 1: Fully initialize
int arr1[5] = {1, 2, 3, 4, 5};
// Method 2: Partially initialize (remaining elements will be automatically initialized to 0)
int arr2[5] = {1, 2, 3}; // arr2[3] and arr2[4] are 0
// Method 3: Do not specify length, compiler calculates automatically
int arr3[] = {1, 2, 3, 4, 5}; // Array length is 5
// Method 4: Fully initialize to 0
int arr4[5] = {0}; // All elements are 0
Special Initialization Techniques:
#include <stdio.h>
int main() {
// Use loop to initialize array
int squares[10];
for (int i = 0; i < 10; i++) {
squares[i] = (i + 1) * (i + 1); // Store squares of 1-10
}
// Use memset for quick initialization (requires string.h)
#include <string.h>
int zeros[100];
memset(zeros, 0, sizeof(zeros)); // Fully initialize to 0
// The third parameter tells memset "how many bytes to set to 0"
// Specifically, sizeof calculates the number of bytes occupied by the variable zeros
// That is, number of elements * size of each element = value of sizeof
// But it's hard to calculate the size of each element manually, so we can generally understand sizeof as:
// Calculating the total number of elements in zeros
return 0;
}// Use the fastest way to fully initialize a 100-element integer array to 0
memset operates on bytes, so it is best suited for initializing “all 0” or “all -1” scenarios (since the binary complement of -1 has all bits as 1, it can also be filled at the byte level). If you want to initialize other values (like 1), you cannot use memset. — For example, if you want to set an int to 1, memset will set each byte to 1, resulting in 0x01010101 (instead of 1), which is not as expected.
Common Questions and Answers
Q: What happens if an array is not initialized?
A: If an array is defined without initialization, the values of the elements are undefined (garbage values). Local arrays defined within functions especially need to be initialized.
Q: Can the array length use variables?
A: In the C89 standard, the array length must be a constant. However, the C99 standard supports variable-length arrays (VLA), but it is recommended to use them cautiously.
3. Referencing and Traversing Array Elements
3.1 Referencing Array Elements
Reference Syntax:
ArrayName[Index]
Index Rules:
-
Index starts from 0 and ends at “Array Length – 1”
-
Index can be an integer constant, variable, or expression
Element Reference Example:
#include <stdio.h>
int main() {
int scores[5] = {85, 92, 78, 90, 88};
// Access a single element
printf("First score: %d\n", scores[0]);
printf("Third score: %d\n", scores[2]);
// Modify element value
scores[1] = 95; // Modify second score
printf("Modified second score: %d\n", scores[1]);
// Use variable as index
int index = 4;
printf("Last score: %d\n", scores[index]);
return 0;
}
3.2 Traversing Arrays
Traversal Method: Use loop structures to access each element sequentially
Traversal Example:
#include <stdio.h>
int main() {
int numbers[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Method 1: For loop traversal
printf("Array elements:");
for (int i = 0; i < 10; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Method 2: While loop traversal
printf("Reverse output:");
int j = 9;
while (j >= 0) {
printf("%d ", numbers[j]);
j--;
}
printf("\n");
return 0;
}
Calculating Array Length Technique:
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]); // Calculate number of elements
printf("Array length: %d\n", length);
In-Class Practical Exercises
Exercise 1: Luogu P1428 Cute Fish Comparison
Problem Description: There are n cute fish, each with a cuteness value. For each fish, calculate how many fish before it are cuter.
Input Format: The first line contains an integer n, the second line contains n integers representing cuteness values
Output Format: n integers representing the result for each fish
Test Case:
Input:
64 3 0 5 1 2
Output:
0 0 0 3 1 2
Code Implementation and Explanation:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int cuteness[100]; // Assume a maximum of 100 fish
int result[100];
// Read cuteness values
for (int i = 0; i < n; i++) {
scanf("%d", &cuteness[i]);
}
// Calculate how many fish before each are cuter
for (int i = 0; i < n; i++) {
int count = 0;
// Traverse all fish before the current one
for (int j = 0; j < i; j++) {
if (cuteness[j] < cuteness[i]) {
count++;
}
}
result[i] = count;
}
// Output results
for (int i = 0; i < n; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
Exercise 2: HDOJ 2006 Product of Odd Numbers
Problem Description: Given n integers, calculate the product of all odd numbers among them.
Input Format: Multiple test cases, each line starts with n followed by n integers
Output Format: The product of odd numbers for each test case
Test Case:
Input:
3 1 2 34 2 4 6 8
Output:
31
Code Implementation and Explanation:
#include <stdio.h>
int main() {
int n;
while (scanf("%d", &n) != EOF) {
int numbers[1000];
long long product = 1; // Use long long to prevent overflow
int hasOdd = 0; // Flag to indicate if there are odd numbers
// Read n integers
for (int i = 0; i < n; i++) {
scanf("%d", &numbers[i]);
}
// Calculate the product of odd numbers
for (int i = 0; i < n; i++) {
if (numbers[i] % 2 != 0) { // If odd
product *= numbers[i];
hasOdd = 1;
}
}
// Output result (if no odd numbers, output 1)
if (hasOdd) {
printf("%lld\n", product);
} else {
printf("1\n");
}
}
return 0;
}
Exercise 3: POJ 2562 Sum of Reversed Numbers
Problem Description: Reverse two numbers, add them, and then reverse the result for output.
Input Format: Multiple sets of data, each line contains two integers a, b (0 ≤ a, b ≤ 10000)
Output Format: The result after reversing the sum
Test Case:
Input:
24 14358 754305 794
Output:
3419981
Code Implementation and Explanation:
#include <stdio.h>// Function to reverse a number
int reverse(int num) {
int reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return reversed;
}
int main() {
int a, b;
while (scanf("%d %d", &a, &b) != EOF) {
// Reverse two numbers
int revA = reverse(a);
int revB = reverse(b);
// Add and then reverse the sum
int sum = revA + revB;
int result = reverse(sum);
printf("%d\n", result);
}
return 0;
}
4. Practical Tips for Array Applications
4.1 Array Boundary Checking
Safe Access Techniques:
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int index;
printf("Please enter the index to access (0-4):");
scanf("%d", &index);
// Boundary check
if (index >= 0 && index < 5) {
printf("arr[%d] = %d\n", index, arr[index]);
} else {
printf("Index out of bounds! Valid range: 0-4\n");
}
return 0;
}
4.2 Counting Array Elements
Counting Example:
#include <stdio.h>
int main() {
int scores[10] = {85, 92, 78, 90, 85, 88, 92, 76, 85, 90};
int count[101] = {0}; // Used to count the number of people scoring 0-100
// Count occurrences of each score
for (int i = 0; i < 10; i++) {
count[scores[i]]++;
}
// Output counting results
printf("Score statistics:\n");
for (int i = 0; i <= 100; i++) {
if (count[i] > 0) {
printf("%d points: %d people\n", i, count[i]);
}
}
return 0;
}
Common Questions and Answers
Q: Why do array indices start from 0 instead of 1?
A: This is to maintain consistency with memory address calculations. The address of the first element of the array is base, and the address of the i-th element is base + i × element size, making it more natural to calculate from 0, avoiding the overhead of subtracting 1 each time you access.
Q: How to avoid out-of-bounds access?
A: 1. Strictly check index ranges; 2. Use sizeof to calculate array length; 3. Use explicit boundary conditions in loops; 4. Use safe library functions.
Q: What should be noted when passing arrays as function parameters?
A: When passing arrays as function parameters, the address of the first element is actually passed, not a copy of the entire array. Therefore, modifying array elements within the function will affect the original array. We will study this in detail in Lesson 18.
In the next lesson, we will learn:
Sorting and searching algorithms for arrays
If you have questions, feel free to comment!
Follow YunJie Algorithm, no textbooks needed, just a few clicks to systematically learn programming!