In C, a character array is a collection of elements of the ‘char’ data type that are placed in contiguous memory locations and are often used to store strings. The length of a character array is defined as the total number of characters present in the array, excluding the null character ('\0'
) at the end. In this article, we will learn how to find the length of a character array in C.
Example:
Input: char arr[] = “Hello, Geek!” Output: Length of the character array is 12
Finding the Size of a Character Array in C
To find the length of a character array in C, we can directly use the strlen()
function from the <string.h>
library. This function returns the length of the character array, excluding the null character.
Syntax to Find Length of Character Array in C
int len = strlen(arr);
Note: The
strlen()
function even work for arrays passed to functions as it finds the length of the array using the NULL character.
C Program to Find Length of Character Array
The below example demonstrates how we can use the strlen() function to find the the length of character array in C.
// C Program to demonstrate how to find the the length of
// character array
#include <stdio.h>
#include <string.h>
int main()
{
// Initializing a character array with some elements
char arr[] = "Hello, Geek!";
// Finding the length of the character array
int length = strlen(arr);
// Printing the length of the character array
printf("Length of the character array is %d\n", length);
return 0;
}
Output
Length of the character array is 12
Time Complexity: O(N), where n is the number of characters in the character array.
Auxilliary Space : O(1)