hi all

i have a integer array of fixed max size(assume 100). But the actual number of stored integers are less than max value(assume 50).Because it is change dynamically. How can i get the actual number of integers stored in the array.

regards
wijitha

Recommended Answers

All 5 Replies

The best way is to keep track of how many integers you've stored with a counter-variable.

no it difficult to do in my application as you suggest. Isn't a way like, how we get the length of char array[].

That's the only way to do it when using basic C-style arrays. If you are writing a c++ program then use std::string instead of char* and you will be able to easily get the array size whenever you need it.

No. Checking the length of a char-array means looking for the first '\0' (end of string). But there is no 'end of int'-int...
But you're using C++, so why not use an int-stack instead of an array?
example:

stack< int > myStack; //init the stack
for (int i = 0; i < 5; i++)
{
    myStack.push(i); //push on stack (add to array)
}
while (!myStack.empty()) //as long as there are ints on the stack
{
    cout << myStack.top() << endl; //show the number that's on top of the stack (last of the array)
    myStack.pop(); //remove the number from stack
}

I didn't test it, but you probably get the idea. This way you don't have to worry about how many ints are in an array.

That's the only way to do it when using basic C-style arrays. If you are writing a c++ program then use std::string instead of char* and you will be able to easily get the array size whenever you need it.

Agreed, but the OP asked for an array of ints, not a char-array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.