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


Counting elements in an array passed to a function?

Recommended Posts

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?

Share this post

Link to post
Share on other sites