简体   繁体   中英

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

I know that in CI 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM