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?
-
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). – Nbr44 Jul 29 '13 at 09:59
-
Note that `strlen` uses terminating null character to find the length, you need something similar for int array, otherwise not possible – P0W Jul 29 '13 at 10:03
-
4You 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. – Jens Gustedt Jul 29 '13 at 10:14
-
Read: [Length of array in C](http://stackoverflow.com/a/18009736/1673391) – Grijesh Chauhan Aug 19 '13 at 17:29
1 Answers
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.

- 601,492
- 42
- 1,072
- 1,490