Archived

This topic is now archived and is closed to further replies.

vbisme

Testing Array Size

Recommended Posts

vbisme    100
let''s say you create an array myArray. Then later you want to test to see how many elements that array has, how would you do that?

Share this post


Link to post
Share on other sites
LilBudyWizer    491
Bigshot''s way is how you do it, but you should get in the habit of keeping a variable with the number of entries in it. An alternative if you have to process every element in the array is to use a sentinal. A c style string uses one at the end, i.e. "\0". A value not used for any other purpose tells you that you hit the end.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Bigshot''s code will only work for static arrays. i.e. if you have "int myArray[15]" then you''ll get 15 back.

If you have a dynamic array it won''t work and will give you the wrong answer. e.g. "myArray = new int[15]". In this case Bigshot''s code will give you the *wrong* answer. You won''t get an error or anything, just the wrong answer.

Be extremely careful when using that.

You''re best bet is just to keep a variable around as LilBudyWizer suggested. You can also use the vector type in STL if you''re using C++

-Mike

Share this post


Link to post
Share on other sites