C array length

This tip shows you how to calculate the length or number of elements in a one-dimensional array by using the sizeof function. To find the length or number of array elements in C, you can use this syntax :
Array_length=sizeof(array_name)/sizeof(data_type);

The example code below calculates the lengths of integer, double, and string arrays.


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main()
{
   int array_length;
   //array initializattion
   int arrint[]={12,10,5,6,7};
   double arrdouble[]={2.0,4.2,3.6,6.5};
   char *arrstring[]={"C","C++","C#","Java"};
   //calculate array length
   array_length=sizeof(arrint)/sizeof(int);
   printf("First Array length=%d\n",array_length);
  
   array_length=sizeof(arrdouble)/sizeof(double);
   printf("Second Array length=%d\n",array_length);
  
   array_length=sizeof(arrstring)/sizeof(char*);
   printf("Third Array length=%d\n",array_length);
  
   getch();
   return 0;
}

Posted by: Lavy | post date: 01-26-2013 | Subject: C Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.