• Advertisement

Archived

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

Counting elements in an array passed to a function?

This topic is 5454 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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.

Share this post


Link to post
Share on other sites

  • Advertisement