Tuesday, July 14, 2009

How to read the length of an array in c language?

i need help with reading the length of an array


i'm really bad with arrays, i'm a beginner at this


ex.


int a[] = {7, 5, 5, 15, 46, 12};





please i'm suffering!!!!!!!!!!!!!!!!!!!!!...

How to read the length of an array in c language?
int arrayLen = (sizeof a)/(sizeof int);
Reply:are you asking how many elements are in that array or for a function to give you the amount of elements in an array?
Reply:Your question is a very good one, since it highlights a big deficiency in the C language. There is no way in C to programmatic determine the length of an array. The person programming this code must use their eye balls to count the integers in the array. In this case the array contains 6 elements. A much safer way to declare this array would be:





#define SIZE 6





int a[SIZE] = {7, 5, 5, 15, 46, 12 };





You can then use the SIZE constant when looping over the array. If you were to add a 7th or 8th element into the array, but forgot to update the SIZE constant you would get a compile time error, which is a good thing, since it is always better to find problems at compile time than at runtime.





If you were using the Java language determining the length of an array is much simpler. Java has a handy length property for all arrays. In your case you would just code "a.length" to determine the length of the array.

carnation

No comments:

Post a Comment