Advertisement

Testing Array Size

Started by November 02, 2000 08:41 PM
3 comments, last by vbisme 24 years, 2 months ago
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?
numElements = sizeof myArray / sizeof myArray[0];


Alex
bigshot@austin.rr.com

Foolish man give wife grand piano. Wise man give wife upright organ.
Alexbigshot@austin.rr.comFoolish man give wife grand piano. Wise man give wife upright organ.
Advertisement
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.
Keys to success: Ability, ambition and opportunity.
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
Good point. That is the perfect example of where you need a class for a beginning programmer or one new to oop.
Keys to success: Ability, ambition and opportunity.

This topic is closed to new replies.

Advertisement