Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any shortcut for array size / length in C?

Tags:

arrays

c

Is there any way to speed up getting an array size in C?

Typing out sizeof(array)/sizeof(int) every time gets old. Do any C libraries have something like .length or is there some way I can define sizeof(array)/sizeof(int) as a shorter constant of some sort (possible also using dot notation)?

like image 690
ubiquibacon Avatar asked Nov 29 '10 20:11

ubiquibacon


People also ask

How do you find the length of an array in C?

Using the sizeof() operator and using pointer arithmetic. The sizeof() operator in C calculates the size of passed variables or datatype in bytes. Therefore to find the array's length, divide the total array size by the size of one datatype that you are using.

How do you find the length of an array array?

With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[]. length; // length can be used // for int[], double[], String[] // to know the length of the arrays.

Is there a length function for arrays in C?

To find the length of the array we have to use sizeof() function. The sizeof() function in C calculates the size in bytes of the passed variable or data type. To calculate the length of array in C, first, calculate the total size of the array and then calculate the size of the data type.

Do I have to specify array size in C?

You can declare an array without a size specifier for the leftmost dimension in multiples cases: as a global variable with extern class storage (the array is defined elsewhere), as a function parameter: int main(int argc, char *argv[]) . In this case the size specified for the leftmost dimension is ignored anyway.


1 Answers

You can use sizeof(array)/sizeof(*array) and make a macro.

#define length(array) (sizeof(array)/sizeof(*(array)))
like image 108
Šimon Tóth Avatar answered Oct 08 '22 07:10

Šimon Tóth