2

I know that in C I can get the length of a char array by using strlen() but how do I get the length of an integer array. Is there a function in a library somewhere?

4
  • The only way you can know the length of such an array is to keep the size in a side variable. Unlike for strings of characters, no value would be valid to mark the end of an array of integers unless one if defined as such (e.g. your array is supposed to only hold positive values and you put a -1 at the end). Commented Jul 29, 2013 at 9:59
  • Note that strlen uses terminating null character to find the length, you need something similar for int array, otherwise not possible Commented Jul 29, 2013 at 10:03
  • 4
    You are under a false assumption. strlen is not for testing char arrays but for testing C strings, that are char arrays plus a special convention for termination. Commented Jul 29, 2013 at 10:14
  • Read: Length of array in C Commented Aug 19, 2013 at 17:29

1 Answer 1

4

In general, you cannot obtain the length of an array unless the array includes a pre-determined terminating sentinel. So, a C string is the canonical example of an array that has a pre-determined terminating sentinel, namely the null terminator.

You will need to keep track of the length of the array in a separate variable, or use a terminating sentinel.

An example of the latter would be an array declared like this:

int array[] = { 1, 2, 42, -1 };

where -1 is deemed to be the terminator. That technique is only viable when you can reserve a value for use as a terminator.

I'm assuming that you are looking to obtain the length of a dynamically allocated array, since that is the most likely scenario for the question to be asked. After all, if your array is declared like this, int array[10], then it's pretty obvious how long it is.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.