Advertisement

Counting elements in an array passed to a function?

Started by March 17, 2003 08:59 PM
0 comments, last by Utwo 21 years, 8 months ago
Hello. I was wondering, suppose I''m passing an array to a function like so:
  
int main()
{

 int x[3] = {1, 34, 6};

 int num_elements = CountElements(&x); 

}

int CountElements(int * array)
{

 // return the number of elements in array passed


}
  
Of course this example is silly but it simple and illustrates the point: since array is simply a pointer to the first element in, in this case, x[], is there any way that CountElements() could possible know how many elements are in that array? I figured I could do a simple sizeof() on the whole array, and then a sizeof() on one element, and then devide the two. However, how is CountElements() possibly to know how large array is if it doens''t know where it ends?
---signature---" Actually, at the time, I didn't give a damn about the FoxNews issue... just that you would come swooping in with your Super Mith cape flapping behind you and debunk it just because it didn't happen in your living room." - InnocuousFox
You can''t do it. When passing an array as a parameter, you will also have to pass its length - or better yet, use a vector rather than a raw array.

This topic is closed to new replies.

Advertisement