How to Find Length of Array in C? Arrays are fundamental data structures in the C programming language, providing a convenient way to store and manipulate collections of elements of the same data type. One common question that arises when working with arrays is how to determine their length. Unlike some high-level programming languages, C does not inherently store the size of an array. In this article, we will explore different methods to find the length of an array in C.
Table of Contents
Length of Array By Using Sizeof Operator
The sizeof
operator in C is a versatile tool that allows programmers to obtain the size of a data type or an object, including arrays. To find the length of an array, you can use the formula:
int array_size = sizeof(array) / sizeof(array[0]);
Here, sizeof(array)
gives the total size of the array, and sizeof(array[0])
gives the size of one element. Dividing the total size by the size of one element gives the number of elements in the array.
C program
#include <stdio.h>
void main() {
int numbers[] = {1, 2, 3, 4, 5};
int array_size = sizeof(numbers) / sizeof(numbers[0]);
printf("The length of the array is: %d\n", array_size);
}
Output
Macro Approach to Find Length of Array in C
To simplify the process of finding the length of an array, you can define a macro that calculates it. This approach enhances code readability and avoids redundancy.
#define ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))
C program
#include <stdio.h>
#define ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))
void main() {
int numbers[] = {1, 2, 3, 4, 5,67,4,2,3};
int array_size = ARRAY_LENGTH(numbers);
printf("The length of the array is: %d\n", array_size);
}
Output
Length of char Array(String) in C
In certain situations, arrays may be terminated with a sentinel value, such as the null character in strings. For example
C program
#include <stdio.h>
void main()
{
char string[] = "Gang for code";
int array_length = 0;
while (string[array_length] != '\0')
{
array_length++;
}
printf("Length of String = %d",array_length);
}
Output
In this approach, the length is determined by iterating through the array until the sentinel value is encountered.
Determining the length of an array in C is essential for effective array manipulation. Whether using the sizeof
operator, defining macros, or employing sentinel values, understanding these methods empowers C programmers to work efficiently with arrays.
Happy Coding
2 thoughts on “How to Find Length of Array in C”