user2381799
user2381799

Reputation:

How do I find the length of an int array in c?

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?

Upvotes: 2

Views: 688

Answers (1)

David Heffernan
David Heffernan

Reputation: 612954

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.

Upvotes: 4

Related Questions