OneBite.Dev - Coding blog in a bite size

find the length of an array in C

Code snippet on how to find the length of an array in C

#include <stdio.h> 

int main() 
{ 
    // Declaring an array 
    int array[10]; 
  
    // Finding the size of the array 
    int length = sizeof(array) / sizeof(array[0]); 
  
    printf("Length of the array is %d\n", length); 
  
    return 0; 
} 

This code starts with including the header file “stdio.h”, which is needed for using the printf() function. Then it declares an integer array of size 10 and finds the length of the array by using the sizeof() operator. Firstly, since the sizeof() operator takes a variable as an argument, we pass the array name as the argument. The sizeof() operator gives the size of the whole array in bytes. In order to find the length, we need to divide the size of the array with the size of one element of array (i.e, size of integer). In the end, the length of the array is printed with the printf() function.

c