954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to get the actual size of int array

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

wijitha
Newbie Poster
12 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

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

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

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

wijitha
Newbie Poster
12 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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.

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 
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.

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You