Durga Prasad Durga Prasad - 3 months ago 9
C Question

How to find length of Array of Undefined size

Given an array with a length defined by it's configuration:

int a[] = {1,2,3,4,5,6,......n}; // Size of the array may change adding/deleting elements


How it's possible to know at runtime the array length, for example to loop on all the array elements without having to manually set the loop limit to n?

int a[] = {1,2,3,4,5};
float b[] = {1.2, 0.1, 3.2};

printf("Array a size is %d\n", dim(a));
printf("Array b size is %d\n", dim(b));


How do you define
dim()
?

Answer

You can implement dim() as:

 #define dim(x) (sizeof(x)/sizeof(x[0]))

adding this define to your code, running it, it prints:

 Array a size is 5
 Array b size is 3
Comments