Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element count of an array in C++

Tags:

c++

arrays

sizeof

Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

I can thing of only one case: the array contains elements that are of different derived types of the type of the array.

Am I right and are there (I am almost positive there must be) other such cases?

Sorry for the trivial question, I am a Java dev and I am rather new to C++.

Thanks!

like image 285
Albus Dumbledore Avatar asked Jan 29 '11 21:01

Albus Dumbledore


People also ask

How do you count elements in an array?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

How do you find the size of an array in C?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.

Which function is used to count elements in an array?

The count() function returns the number of elements in an array.

What is count in array?

Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.


1 Answers

Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

One thing I've often seen new programmers doing this:

void f(Sample *arr) {    int count = sizeof(arr)/sizeof(arr[0]); //what would be count? 10? }  Sample arr[10]; f(arr); 

So new programmers think the value of count will be 10. But that's wrong.

Even this is wrong:

void g(Sample arr[]) //even more deceptive form! {    int count = sizeof(arr)/sizeof(arr[0]); //count would not be 10   } 

It's all because once you pass an array to any of these functions, it becomes pointer type, and so sizeof(arr) would give the size of pointer, not array!


EDIT:

The following is an elegant way you can pass an array to a function, without letting it to decay into pointer type:

template<size_t N> void h(Sample (&arr)[N]) {     size_t count = N; //N is 10, so would be count!     //you can even do this now:     //size_t count = sizeof(arr)/sizeof(arr[0]);  it'll return 10! } Sample arr[10]; h(arr); //pass : same as before! 
like image 97
Nawaz Avatar answered Oct 01 '22 14:10

Nawaz