One-dimensional array: A collection of elements of the same data type stored in contiguous memory locations, where each element can be accessed using an index starting from 0.
Declaring an array: You create a one-dimensional array by specifying its data type, array name, and size between square brackets.
int myArray[10]; // Declares an array named "myArray" with 10 integer elements
Initializing an array: Assigning initial values to the elements when declaring them:
int myArray[] = {1, 2, 3, 4, 5}; // Declares and initializes an array of 5 integers
Accessing an element: Use the index operator ([]) to access a specific element in the array.
printf("%d", myArray[0]); // Outputs the first element's value (1)
Here's a simple example that takes user input and stores it in an array:
#include <stdio.h>
int main() {
int numbers[5]; // Declare an array to hold 5 integers
for (int i = 0; i < 5; ++i) {
printf("Enter number %d: ", i + 1);
scanf("%d", &numbers[i]); // Read user input and store it in the current index of the array
}
for (int i = 0; i < 5; ++i) {
printf("Number %d: %d\n", i + 1, numbers[i]); // Print each number and its corresponding position
}
return 0;
}
What causes it: Accessing an index beyond the array's size.
# Bad code example that triggers the error
int myArray[5];
printf("%d", myArray[5]); // Index 5 exceeds the array's size (4 elements)
Error message:
Segmentation fault: 11
Solution: Make sure that the index is within the array's bounds.
# Corrected code
int myArray[5];
for (int i = 0; i < 5; ++i) {
printf("%d", myArray[i]); // Now, this loop only accesses valid indices (0 to 4)
}
Why it happens: The array has a fixed size, and accessing an index beyond that size results in undefined behavior.
How to prevent it: Verify that the index is less than the array's size before attempting to access its value.
What causes it: Declaring large arrays consumes too much memory for the current environment, leading to a memory error or crash.
# Bad code example that triggers the error
int myArray[100000]; // Declare an array with 100,000 elements
Error message:
Segmentation fault: 11
Solution: Reduce the size of the array or allocate memory dynamically using malloc().
# Corrected code (using dynamic memory allocation)
#include <stdlib.h>
int main() {
int *myArray = (int *)malloc(100000 * sizeof(int)); // Allocate 100,000 integers dynamically
// ... use myArray here ...
free(myArray); // Don't forget to free the memory after using it!
return 0;
}
Why it happens: Large arrays require a significant amount of memory, which may not be available in some environments.
How to prevent it: Be aware of the resources available in your environment and limit the size of arrays accordingly. If necessary, use dynamic memory allocation instead.