# array length

• 08-30-2003
Wick
array length
I realized that strlen() only works on arrays of characters. I need to find a way to get the length of an array such as:
Code:

int array[10];

array[0] = 1;
array[1] = 1;
array[2] = 1;

The answer would obviously be 3.
I came up with this cheat that works in most cases:
Code:

int length = 0;

for (int x = 0; array[x]; ++x)
{
++length;
}

return length;

it works for the above example, but for cases like array[1] = 0; the for loop would terminate on array[1], causing the length to return as 1.

What's a good way to find the length of any type of array?

edit: Changing array[x]; to array[x] || array[x] == 0; won't work as there are a few ways my cheat can be disrupted.
• 08-30-2003
gustavosserra
As far as I know, you canīt do this. But to declare an array you must use a fixed size, either with static or dynamic allocation. I think that you could use the vector class if you want this kind of thing anyway!
• 08-30-2003
Lynux-Penguin
Code:

int len = sizeof(myArray) / sizeof(myArray[0]);
-LC
• 08-30-2003
Cat
This fails, however, when you pass the array to a function, which is why I never rely on that method.

Wick, the best way is to not use arrays at all. Use a std::vector. It's as easy to use as an array, and you have the .size() method to tell you its size.

Example:

Code:

#include <vector>
#include <iostream>

typedef std::vector<int> intArray;

void printArray(intArray ia){
for (int i = 0; i < (int) ia.size(); i++){
std::cout << "[" << ia[i] << "]";
}
}

int main(){
intArray myArray(20); //creates an array of 20 elements
for (int i = 0; i < (int) myArray.size(); i++)
myArray[i] = 2* i;
printArray(myArray);
}

In 95% of cases, std::vector can be substituted freely for an array with minimal effort, and it's the better choice to use.