View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Understanding One Dimensional Array in C: Key Concepts and Usage

Updated on 30/04/20254,875 Views

Effective data organization is fundamental to writing robust and efficient programs. In the C programming language, one of the most essential tools for achieving this is the one dimensional array in C. Despite its simplicity, this structure provides a reliable and organized method for storing sequences of data in contiguous memory locations. That’s why this concept is also a part of every highly-recommended software development course

This article explores the one dimensional array in C, focusing on its structure, usage, and best practices. Before we examine its practical implementation and common use cases, it's important to revisit some foundational concepts to ensure a clear understanding moving forward.

What is an Array?

In simple terms, an array is a collection of similar data types stored in contiguous memory locations. It is a fundamental data structure that enables storing and organizing multiple data items of the same type. The advantage of arrays is that they allow you to access data via a single, common name, using an index or subscript that can locate each individual element.

Types of Arrays

Primarily, arrays can be categorized into two types:

  1. One-dimensional arrays (1D Arrays): These are simple list-like structures that store data linearly.
  2. Multi-dimensional arrays (2D, 3D, etc.): Multidimensional arrays including three or two-dimensional array in C are complex structures that store data in a matrix format.

In this article, we'll focus on the one dimensional array in C and compare it with its C++ equivalent at places. 

What is One Dimensional Array in C

One-dimensional arrays are the simplest form of arrays that consist of a collection of elements of the same data type arranged in sequential memory locations. Consider a one-dimensional array as a single row where you can store multiple items of the same data type.

Unlock a high-paying career with following full-stack development courses:

Array Declaration

Before an array can be used in a C program, it must be declared. The syntax for declaring an array is as follows:

datatype arrayName[arraySize];

Here, the datatype can be any valid C data type, the arrayName is the name of the array, and the arraySize is an integer constant greater than zero, representing the number of elements that can be stored in the array.

In addition, you should explore our article on structure of a C program to learn how to build an efficient array program. 

Array Initialization

Once a one dimensional array in C is declared, it can be initialized with values to assign data to each element. This allows for an immediate and organized population of the array during its creation. The general syntax for array initialization is:

datatype arrayName[arraySize] = {element1, element2, ..., elementN};

Example 1: Initializing with specific values

int num[5] = {1, 2, 3, 4, 5};

In this example, a one dimensional array in C named num is declared with five elements and initialized with the values 1 through 5. Each element is stored in a contiguous memory location, starting at index 0.

Example 2: Initializing all elements to zero

int zeros[5] = {0};

This approach initializes only the first element explicitly, while the remaining elements are automatically set to 0 by default. It's a common technique for clearing or resetting a one dimensional array in C during declaration.

Accessing Elements in a One Dimensional Array

Elements in an array can be accessed using their respective index. The index of an array starts from 0 and goes up to n-1 where n is the size of the array.

Syntax:

arrayName[index]; 

This syntax retrieves the value stored at the specified index of the array.

Example:

#include <stdio.h>

int main() {
   int num[5] = {1, 2, 3, 4, 5};
   printf("%d", num[2]);
   return 0;
}

In this example, a one dimensional array in C named num is declared and initialized with five integer values. The expression num[2] accesses the third element in the array (since indexing starts from 0), and the program will print 3 as output.

C Program to Illustrate Declaration, Initialization, and Accessing of Elements of a One Dimensional Array in C

The following program demonstrates how to declare a one dimensional array in C, initialize it with values, and access its elements using index positions:

#include <stdio.h>

int main() {
    // Declaration and initialization of a one dimensional array in C
    int numbers[5] = {10, 20, 30, 40, 50};

    // Accessing and printing array elements
    printf("First element: %d\n", numbers[0]);
    printf("Third element: %d\n", numbers[2]);
    printf("Fifth element: %d\n", numbers[4]);

    return 0;
}

Output:

First element: 10
Third element: 30
Fifth element: 50

Explanation:

In this program, a one dimensional array in C named `numbers` is declared with five integer elements. The array is initialized at the time of declaration with the values `{10, 20, 30, 40, 50}`.

Each element is accessed using its index:

  • `numbers[0]` refers to the first element (`10`)
  • `numbers[2]` refers to the third element (`30`)
  • `numbers[4]` refers to the fifth element (`50`)

This simple example demonstrates the fundamental operations: declaration, initialization, and element access, that form the basis of working with arrays in C.

Furthermore, if you use operating systems, other than Windows, then you should explore our detailed articles on: 

Rules for Declaring One Dimensional Array in C

Declaring a one dimensional array in C involves a set of rules and regulations that must be strictly followed to ensure the correct functionality of the program. Here are some crucial rules:

Fixed Size

The size of the array should be defined at the time of declaration. The size must be a constant integer, i.e., it cannot be a variable or a dynamic expression.

int arr[5]; // Valid

int size = 5;

int arr[size]; // Invalid in C, size should be a constant

No Negative Dimension

The size of the array must be greater than zero. Negative or zero dimensions are not allowed.

int arr[5]; // Valid

int arr[0]; // Invalid

int arr[-5]; // Invalid

Data Type

The elements of an array should all be of the same data type. You cannot have an array with mixed data types.

int arr[5]; // Valid

int arr[5] = {1, "two", 3, "four", 5}; // Invalid, mixed data types

Array Initialization

If you initialise an array at the time of declaration, ensure that the number of elements does not exceed the specified size. You can, however, initialise an array with fewer elements than specified, and the remaining elements will automatically be assigned the default value of the data type (0 for integers, 0.0 for floats, '\0' for characters).

int arr[5] = {1, 2, 3, 4, 5}; // Valid

int arr[5] = {1, 2, 3}; // Valid, the remaining elements will be set to 0

int arr[5] = {1, 2, 3, 4, 5, 6}; // Invalid, more elements than specified

Array Name

The array name should follow the rules for identifiers in C. It can contain alphabets, digits, and underscores. However, it cannot begin with a digit.

int arr[5]; // Valid

int 1arr[5]; // Invalid, identifier starts with digit

Initialization of One-Dimensional Array in C

There are two primary methods of initializing a one dimensional array in C.

Compile-Time Initialization of One-Dimensional Array in C

This method involves initializing an array at the time of its declaration. In this case, the size and elements of the array are defined at compile time.

Syntax:

datatype arrayName[arraySize] = {value1, value2, ..., valueN};

  • datatype is the type of data (e.g., int, float, char)
  • arrayName is the name of the array
  • arraySize is the number of elements
  • {value1, value2, ..., valueN} is the list of values assigned at declaration

Example:

int num[5] = {1, 2, 3, 4, 5};

This line declares a one dimensional array in C named num with 5 integer elements and initializes them with the values 1 to 5.

Complete Program:

#include <stdio.h>

int main() {
    // Compile-time initialization of a one dimensional array in C
    int num[5] = {1, 2, 3, 4, 5};

    // Printing the array elements
    for(int i = 0; i < 5; i++) {
        printf("Element at index %d: %d\n", i, num[i]);
    }

    return 0;
}

Output:

Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5

Explanation:

In this program, a one dimensional array in C called num is declared and initialized during compile time with the values {1, 2, 3, 4, 5}. The for loop iterates through the array from index 0 to 4 and prints each element.

Since the values are hardcoded into the source code, the compiler stores them directly in memory during the compilation process. This approach is highly efficient and ideal when the data set is fixed and known in advance.

Must Explore: Static Function in C: Definition, Examples & Real-World Applications

Run-Time Initialization of One Dimensional Array in C

In run-time initialization, the array is initialized during the execution of the program, not at the compile time. This is particularly useful when inserting values into an array based on user input or some computations.

Syntax:

datatype arrayName[arraySize];
for(int i = 0; i < arraySize; i++) {
    // Assign value to array elements
    arrayName[i] = value;  // Value can come from user input or calculations
}

Example:

int num[5];
for(int i = 0; i < 5; i++) {
    printf("Enter the element for index %d: ", i);
    scanf("%d", &num[i]);
}

In this example, a one dimensional array in C named num is declared without initialization. The program then asks the user to input five integers, one by one, and stores these values in the array.

Complete Program:

#include <stdio.h>

int main() {
    // Declaration of the one dimensional array in C
    int num[5];
    
    // Run-time initialization using user input
    for(int i = 0; i < 5; i++) {
        printf("Enter the element for index %d: ", i);
        scanf("%d", &num[i]);
    }
    
    // Printing the elements of the array
    printf("\nThe elements of the array are:\n");
    for(int i = 0; i < 5; i++) {
        printf("Element at index %d: %d\n", i, num[i]);
    }

    return 0;
}

Output:

Enter the element for index 0: 10
Enter the element for index 1: 20
Enter the element for index 2: 30
Enter the element for index 3: 40
Enter the element for index 4: 50

The elements of the array are:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Explanation:

In this program, a one dimensional array in C named num is declared with a size of 5. The program then uses a for loop to prompt the user to enter values for each element of the array. The scanf() function is used to read the user input and store it in the corresponding index of the array.

After the values have been entered, another loop is used to print the elements of the array, showing the values that the user entered.

This method of run-time initialization is powerful when the data is dynamic and depends on factors that are only known during program execution, such as user input or real-time computations.

Also read the strlen() Function in C article!

Copying One Dimensional Array in C

Copying the contents of a one dimensional array in C to another requires iterating through each element and assigning the corresponding values. There are several methods to achieve this, including using a for loop, the memcpy() function, and pointers for more flexibility.

Method 1: Using a For Loop

This is the simplest method to copy elements from one array to another using the for loop in C. It involves iterating over each element of the source array and copying it to the corresponding position in the destination array.

Example:

int num1[5] = {1, 2, 3, 4, 5};
int num2[5];

for(int i = 0; i < 5; i++) {
    num2[i] = num1[i];
}

// Printing elements of array num2
for(int i = 0; i < 5; i++) {
    printf("%d ", num2[i]);
}

Complete Program:

#include <stdio.h>

int main() {
    // Declaration and initialization of the first array
    int num1[5] = {1, 2, 3, 4, 5};
    
    // Declaration of the second array
    int num2[5];
    
    // Copying elements of num1 to num2 using a for loop
    for(int i = 0; i < 5; i++) {
        num2[i] = num1[i];
    }

    // Printing elements of array num2
    printf("Elements of num2 after copying:\n");
    for(int i = 0; i < 5; i++) {
        printf("%d ", num2[i]);
    }

    return 0;
}

Output:

Elements of num2 after copying:
1 2 3 4 5

Explanation:

In this program, a one-dimensional array in C named num1 is initialized with values {1, 2, 3, 4, 5}. Another array, num2, is declared to hold the copied values. A for loop iterates through each index of num1 and assigns its corresponding value to num2. The second for loop prints the elements of num2, confirming that the elements have been successfully copied from num1.

This approach is particularly useful when you need to duplicate an array's contents, but keep the arrays separate so that changes to one array do not affect the other.

Method 2: Using memcpy() Function

The memcpy() function, from the C standard library function, allows you to copy the contents of one array to another more efficiently than using a for loop. It performs a bitwise copy of data, which can be faster, especially for larger arrays.

Example:

#include <stdio.h>
#include <string.h>

int main() {
    // Declaration and initialization of the first array
    int num1[5] = {1, 2, 3, 4, 5};
    
    // Declaration of the second array
    int num2[5];
    
    // Copying elements of num1 to num2 using memcpy
    memcpy(num2, num1, sizeof(num1));

    // Printing elements of array num2
    printf("Elements of num2 after copying using memcpy:\n");
    for(int i = 0; i < 5; i++) {
        printf("%d ", num2[i]);
    }

    return 0;
}

Output:

Elements of num2 after copying using memcpy:
1 2 3 4 5

Explanation:

In this approach, we use the memcpy() function to copy the entire contents of the num1 array into the num2 array. The third argument to memcpy() specifies the number of bytes to copy, which is the size of the num1 array. This function is faster than using a for loop, especially when dealing with larger arrays, as it copies the data in blocks.

Method 3: Using Pointers

Pointers in C provide a more flexible way to copy arrays. Using pointer arithmetic, you can access and copy the elements of an array. This method is particularly useful when dealing with dynamically allocated memory or when you want to work with raw memory manipulation.

Example:

#include <stdio.h>

int main() {
    // Declaration and initialization of the first array
    int num1[5] = {1, 2, 3, 4, 5};
    
    // Declaration of the second array
    int num2[5];
    
    // Using pointers to copy elements of num1 to num2
    int *ptr1 = num1; // Pointer to the first array
    int *ptr2 = num2; // Pointer to the second array

    for (int i = 0; i < 5; i++) {
        *(ptr2 + i) = *(ptr1 + i); // Copying elements using pointer arithmetic
    }

    // Printing elements of array num2
    printf("Elements of num2 after copying using pointers:\n");
    for (int i = 0; i < 5; i++) {
        printf("%d ", num2[i]);
    }

    return 0;
}

Output:

Elements of num2 after copying using pointers:
1 2 3 4 5

Explanation:

In this method, we use pointers to copy the elements from num1 to num2. The pointers ptr1 and ptr2 point to the beginning of num1 and num2, respectively. Using pointer arithmetic, we copy each element from num1 to num2. The expression *(ptr2 + i) accesses the i-th element of num2, and *(ptr1 + i) accesses the i-th element of num1.

This method is particularly useful when you're dealing with dynamic arrays, as pointers provide flexibility in working with memory directly. 

Additionally, to understand the details of array, explore our article on length of an array in C

Difference Between One-Dimensional Array in C++ and One Dimensional Array in C

While the fundamental concept of arrays remains consistent in both C and C++, there are subtle differences in functionality and features between the two languages. Let's compare these two side by side:

Syntax

In C++, the syntax for declaring and initialising an array is the same as in C.

C:

int arr[5] = {1, 2, 3, 4, 5};

C++:

int arr[5] = {1, 2, 3, 4, 5};

The syntax remains the same in both languages.

Sizeof Operator

In both C and C++, the sizeof operator can be used to find the size of an array. However, this only works if the array is in the scope because C and C++ don’t support reflection.

C:

int arr[5] = {1, 2, 3, 4, 5};

int size = sizeof(arr)/sizeof(arr[0]);

printf("Number of elements in arr[] is: %d", size);

C++:

int arr[5] = {1, 2, 3, 4, 5};

int size = sizeof(arr)/sizeof(arr[0]);

cout << "Number of elements in arr[] is: " << size;

The result will be '5' in both cases.

Array Initialization

In C++, you have the flexibility to initialise an array without explicitly specifying the number of elements it will contain.

C:

In C, you have to provide the number of elements.

int arr[3] = {1, 2, 3}; // Valid

int arr[] = {1, 2, 3}; // Invalid

C++:

In C++, you don't have to provide the number of elements.

int arr[3] = {1, 2, 3}; // Valid

int arr[] = {1, 2, 3}; // Also Valid

The second declaration is invalid in C but valid in C++.

Must Explore: Enumeration (or enum) in C article!

Standard Template Library (STL)

C++ provides the Standard Template Library (STL), which offers a set of template classes like vector and array. These classes provide more flexible and safer array operations compared to traditional C-style arrays.

C:

In C, we don't have STL, so we have to manually manage array operations.

int arr[5] = {1, 2, 3, 4, 5};

// Manual operation required for traversing, sorting, etc.

C++:

In C++, using STL, we can handle arrays much more efficiently.

#include<vector>

using namespace std;


vector<int> v = {1, 2, 3, 4, 5}; //dynamic size, can be resized

// Inbuilt functions for traversing, sorting, etc.

Common Operations and Functions on One Dimensional Arrays in C

Here’s the detailed table, helping you understand common operations and function of one dimensional array in C. 

Operation

Description

Example/Function

Declaration and Initialization

Declaring and initializing a one dimensional array in C with values.

int arr[5] = {1, 2, 3, 4, 5};

Accessing Elements

Accessing individual elements of a one dimensional array in C using an index.

arr[0], arr[4]

Copying Arrays

Copying the contents of one array to another one dimensional array in C using a loop.

arr2[i] = arr1[i];

Array Traversal

Iterating over a one dimensional array in C to process each element.

for (int i = 0; i < n; i++)

Finding Array Length

Determining the number of elements in an array.

sizeof(arr) / sizeof(arr[0])

Modifying Array Elements

Changing the value of elements in a one dimensional array in C using the index.

arr[2] = 10;

Sorting Arrays

Sorting the elements of an array in ascending or descending order.

qsort() (from stdlib.h)

Searching for an Element

Searching for a specific value in an array.

Linear search

Points to Remember About One Dimensional Array in C

One Dimensional array in C are fundamental constructs that underpin many more complex data structures and algorithms. Here are some essential points to remember about arrays in C, focusing primarily on one-dimensional arrays:

Fixed Size

Once declared, the size of an array in C is fixed. You cannot resize it or change its length dynamically. This is why it's crucial to know the required size of the array beforehand.

Homogeneous Elements

An array in C can only contain elements of the same data type. It cannot store mixed data types. Consider using a structure or union if you need a data structure that can store different data types.

Indexing

Array indexing in C starts from 0. That means the first element of the array is accessed with index 0, the second element with index 1, and so on. Accessing an array outside of its bounds results in undefined behavior, which could lead to program crashes or unpredictable results.

Memory

Array elements are stored in contiguous memory locations, which allows quick access to elements but can also lead to problems if not handled correctly, such as buffer overflow.

Initialization

Arrays in C can be initialized at the time of declaration. However, if an array is partially initialized, elements that are not explicitly initialized receive the default value of the data type (which is 0 for numeric types).

Arrays and Pointers

In C, arrays are closely related to pointers. An array's name acts as a pointer to its first element. This relationship is exploited in various ways in C programming, such as passing arrays to functions, dynamic memory allocation, etc.

No Bounds Checking

C does not perform any bounds checking for arrays. If you try to access or store a value in an array using an index that is outside the valid range, the compiler will not flag an error. However, this could cause serious issues, such as accessing or overwriting memory that the program does not own.

Multidimensionality

While this article primarily focuses on one-dimensional arrays, it's crucial to remember that arrays in C can be multidimensional. This feature allows you to create more complex structures, such as tables, matrices, and even tensors.

By keeping these points in mind while working with arrays in C, you can avoid common pitfalls and understand better how these crucial data structures work. 

Importance of One Dimensional Array in C for Programming

The one dimensional array in C is a fundamental data structure that enables efficient storage and management of multiple elements of the same type. They play a key role in computer programming, providing an easy and efficient way to handle large sets of related data.

1. Efficient Data Storage: A one dimensional array in C allows developers to store multiple values in a single variable, simplifying the management of data.

2. Fast Access to Elements: One dimensional array offer constant-time access to elements, enabling quick retrieval and modification of data using an index.

3. Memory Management: With contiguous memory allocation, a one dimensional array in C optimizes memory usage and ensures efficient storage of elements.

4. Simplified Code: Using a one dimensional array in C reduces code complexity, making it easier to manage large amounts of related data in algorithms.

5. Versatility: A one dimensional array in C can be employed in various algorithms such as searching, sorting, and data manipulation, forming the backbone of many computational tasks. 

Conclusion

As we conclude, we understand that the one dimensional array in C is a powerful data structure. It offers simplicity while allowing us to handle large datasets. You can significantly improve your programming and problem-solving skills by understanding and mastering the concepts of arrays in C.

Additionally, the flexibility of arrays makes them a go-to solution in many scenarios, from storing sequential data to implementing algorithms like sorting and searching. Developing a strong understanding of one dimensional array in C can be the key to building efficient and scalable programs, paving the way for more advanced topics in computer science.

FAQs 

1. What is the difference between a one dimensional array in C and a multi-dimensional array?

A one dimensional array in C consists of a single row of elements, while a multi-dimensional array can hold data in multiple rows and columns (like a matrix). For example, `int arr[3][3];` is a two-dimensional array, whereas a one-dimensional array is just a single sequence of elements, accessed by one index.

2. Can a one dimensional array in C hold different data types?

No, a one dimensional array in C can only hold elements of the same data type. If you need to store different types of data, you could use a `struct`, which allows the grouping of different data types under one name. Arrays are strictly homogeneous, meaning all elements must have the same type.

3. How can a one dimensional array in C be dynamically allocated?

A one dimensional array in C can be dynamically allocated using functions like `malloc()` or `calloc()` from the C standard library. For example, `int *arr = (int *)malloc(sizeof(int) * 5);` dynamically allocates memory for an array of 5 integers. It allows you to allocate arrays whose size is determined at runtime.

4. What happens if you access an out-of-bounds index in a one dimensional array in C?

Accessing an out-of-bounds index in a one dimensional array in C leads to undefined behavior. It may result in accessing random memory locations, causing data corruption, program crashes, or unexpected results. Always ensure that array indices are within the valid range (0 to size-1) to avoid such issues.

5. What is the significance of the `sizeof()` operator with one dimensional array in C?

The `sizeof()` operator in C can be used to determine the total memory size occupied by a one dimensional array. For example, `sizeof(arr)` gives the size in bytes, while `sizeof(arr)/sizeof(arr[0])` calculates the number of elements in the array. This is useful for dynamically allocated arrays and memory management.

6. Can a one dimensional array in C be passed to a function?

Yes, a one dimensional array in C can be passed to a function by passing its reference (pointer) to the function. Arrays in C are passed by reference, meaning that any changes made to the array within the function will reflect in the original array outside the function.

7. How can you find the length of a one dimensional array in C?

In C, the length of a one dimensional array is typically calculated using `sizeof(arr) / sizeof(arr[0])`. This gives the total number of elements in the array. However, this method only works for arrays whose size is known at compile time. For dynamically allocated arrays, additional tracking is needed.

8. What is the role of the `const` keyword with one dimensional array in C?

The `const` keyword can be used with a one dimensional array in C to make the elements of the array read-only. For example, `const int arr[5] = {1, 2, 3, 4, 5};` prevents modification of the array’s elements. This is useful when you want to ensure the data remains constant throughout the program.

9. How can you resize a one dimensional array in C?

In C, arrays cannot be resized after they have been declared. However, you can achieve resizing by allocating new memory using `malloc()` or `realloc()`, copying the contents of the original array to the new memory, and then freeing the old array. This approach is commonly used with dynamic arrays.

10. What are the benefits of using a one dimensional array in C over other data structures?

One dimensional array are simple and efficient for storing sequential data. They offer fast access times and low overhead, making them ideal for storing fixed-size collections of elements. While other data structures like linked lists may offer flexibility, arrays provide constant-time access and are easier to implement.

11. Can a one dimensional array in C store strings?

Yes, a one dimensional array in C can store strings, but each string must be terminated by a null character (`'\0'`). For example, `char str[6] = "Hello";` creates an array that holds the characters of the string "Hello", with the last character being the null terminator. 

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.