Testing Array Size
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.
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.
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.
November 07, 2000 02:41 PM
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
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement