C Array Basics
What is a C Array?
In C programming, an array is a fundamental data structure that allows you to store multiple elements of the same data type in a contiguous memory block. Arrays provide a way to organize and manage collections of data efficiently.
Array Declaration and Initialization
Basic Array Declaration
int numbers[5]; // Declares an integer array with 5 elements
char letters[10]; // Declares a character array with 10 elements
Array Initialization Methods
// Method 1: Direct initialization
int scores[3] = {85, 90, 95};
// Method 2: Partial initialization
int ages[5] = {20, 25}; // Remaining elements are zero-initialized
// Method 3: Complete initialization
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Array Memory Layout
graph LR
A[Memory Address] --> B[First Element]
B --> C[Second Element]
C --> D[Third Element]
D --> E[Fourth Element]
Key Characteristics of Arrays
Characteristic |
Description |
Fixed Size |
Arrays have a predetermined size that cannot be changed dynamically |
Zero-Indexed |
First element is accessed at index 0 |
Contiguous Memory |
Elements are stored in adjacent memory locations |
Type Consistency |
All elements must be of the same data type |
Array Access and Manipulation
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing elements
int firstElement = numbers[0]; // 10
int thirdElement = numbers[2]; // 30
// Modifying elements
numbers[1] = 25; // Changes second element to 25
Common Array Operations
Iterating Through an Array
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
Passing Arrays to Functions
void processArray(int arr[], int size) {
// Function that works with array
}
Best Practices
- Always check array bounds to prevent buffer overflows
- Initialize arrays before use
- Be cautious with array indexing
- Use meaningful variable names
LabEx Tip
When learning array manipulation, practice is key. LabEx provides interactive coding environments to help you master array concepts effectively.