Hi,
So how exactly do we take the length of an int array? Lets say that there is an array called int nums []={2, 1, 2, 3, 4};
Is there a function that can be used to find it?

Recommended Answers

All 8 Replies

Please hurry....I need it really soon...

In this case you can sizeof. sizeof returns the amount of Bytes the element is using. So the idea is to find the sizeof(array) (in your case which will be 20) and the sizeof(int). The size of an int is 4 Bytes.

So now you can use the Math and figure out how to find the array size using this two values.

Hope that helps :)

Next time show some code ok?
int foo = sizeof(array)/sizeof(int);

Ok, next time I will show my code.

Ok, next time I will show my code.

That works only for arrays that are declared in the same function -- it does not work with pointers or arrays passed to other functions (which are also pointers).

A better way is not to use arrays at all but to use c++ std::vector class, which is a like a smart array. But you probably are not allowed to use std::vector yet.

If you are passing an array to a function, here are some standard techniques in C/C++:

  1. pass a 2nd argument with array length (very common, especially in C, e.g. main())
  2. use std template library (all of them have .size() operations) (very common)
  3. only pass arrays of pointers and you can null terminate the array so that loops will know when to stop iterating through the array. But this is no good for e.g. binary searches and is uncommon.
commented: Check those discussion dates. -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.