Как получить количество элементов массива?
Как получить количество элементов массива GET
Доброго времени суток. В адресной строке: ?a1=1&b1=11&a2=2&a3=3&b3=33и так далее (общее количество.
Получить количество отрицательных элементов и количество нулевых элементов массива
Дан массив А из n действительных чисел: a1, …, an. Вычислить: a12, a1a2, a1a3, …, a1an;.
Получить количество отрицательных элементов массива и произведение элементов, принадлежащих отрезку
Дан массив действительных чисел а1,…, аn. Получить количество отрицательных элементов массива и.
Сообщение от Ice_and_Fire
Сообщение от Ice_and_Fire
Получить определенное количество элементов массива
Есть массив ar он добывается с помощью ajax (запуск ajax происходит при клике по button) Сперва.
Получить количество отрицательных элементов массива
Дан массив действительных чисел а1,…, аn. Получить количество отрицательных элементов массива и.
Получить заданное количество случайных элементов массива
Привет! Нужно чтобы из столбца "Список" выводилось Х количество случайно выбранных слов. Для этого.
Получить количество элементов массива, которые не повторяются
Задан массив А(n),некоторые элементы в нем могут встречаться несколько раз.Получить количество.
How can I find the number of elements in an array?
I have an int array and I need to find the number of elements in it. I know it has something to do with sizeof but I’m not sure how to use it exactly.
16 Answers 16
If you have your array in scope you can use sizeof to determine its size in bytes and use the division to calculate the number of elements:
If you receive an array as a function argument or allocate an array in heap you can not determine its size using the sizeof . You’ll have to store/pass the size information somehow to be able to use it:
and you can use another way to make your code not be hard-coded to int
Say if you have an array array
you just need to:
I personally think that sizeof(a) / sizeof(*a) looks cleaner.
I also prefer to define it as a macro:
Then you can use it in for-loops, thusly:
It is not possible to find the number of elements in an array unless it is a character array. Consider the below example:
The above value gives us value 100 even if the number of elements is five. If it is a character array, you can search linearly for the null string at the end of the array and increase the counter as you go through.
In real we can’t count how many elements are store in array
But you can find the array length or size using sizeof operator.
But why we can’t find how many elements are present in my array.
Because when we initialise an array compiler give memory on our program like a[10] (10 blocks of 4 size) and every block has garbage value if we put some value in some index like a[0]=1,a[1]=2,a[3]=8; and other block has garbage value no one can tell which value is garbage and which value is not garbage that’s a reason we cannot calculate how many elements in an array. I hope this will help you to understand. Little concept
Just divide the number of allocated bytes by the number of bytes of the array’s data type using sizeof() .
For example, given an integer array called myArray
Now, if the data type of your array isn’t constant and could possibly change, then make the divisor in the equation use the size of the first value as the size of the data type.
This way, the code is type agnostic and will function correctly no matter the data type of the array.
![]()
I used following code as suggested above to evaluate number of elements in my 2-dimensional array:
It works nicely. As far as I know you can’t mix up different data types in C arrays and also you should have the same size of all array elements (if I am right), therefore you can take advantage of that with this little trick:
- count number of bytes with sizeof() function from whole 2d array (in this case 3*20 = 60 bytes)
- count number of bytes with sizeof() function from first array element strs[0] (in this case 20 bytes)
- divide whole size with size of one element what will give you number of elements
This snipped should be portable for 2d arrays in C however in other programming languages it could not work because you can use different data types within array with different sizes (like in JAVA).
The question is simple: given a C++ array (e.g. x as in int x[10] ), how would you get the number of elements in it?
An obvious solution is the following macro (definition 1):
I cannot say this isn’t correct, because it does give the right answer when you give it an array. However, the same expression gives you something bogus when you supply something that is not an array. For example, if you have
then countof( p ) always give you 1 on a machine where an int pointer and an int have the same size (e.g. on a Win32 platform).
This macro also wrongfully accepts any object of a class that has a member function operator[]. For example, suppose you write
then sizeof( x ) will be the size of the x object, not the size of the buffer pointed to by x.p . Therefore you won’t get a correct answer by countof( x ) .
So we conclude that definition 1 is not good because the compiler does not prevent you from misusing it. It fails to enforce that only an array can be passed in.
What is a better option?
Well, if we want the compiler to ensure that the parameter to countof is always an array, we have to find a context where only an array is allowed. The same context should reject any non-array expression.
Some beginners may try this (definition 2):
They figure, this template function will accept an array of N elements and return N.
Unfortunately, this doesn’t compile because C++ treats an array parameter the same as a pointer parameter, i.e. the above definition is equivalent to:
It now becomes obvious that the function body has no way of knowing what N is.
However, if a function expects an array reference, then the compiler does make sure that the size of the actual parameter matches the declaration. This means we can make definition 2 work with a minor modification (definition 3):
This countof works very well and you cannot fool it by giving it a pointer. However, it is a function, not a macro. This means you cannot use it where a compile time constant is expected. In particular, you cannot write something like:
Can we do anything about it?
Someone (I don’t know who it is – I just saw it in a piece of code from an unknown author) came up with a clever idea: moving N from the body of the function to the return type (e.g. make the function return an array of N elements), then we can get the value of N without actually calling the function.
To be precise, we have to make the function return an array reference, as C++ does not allow you to return an array directly.
The implementation of this is:
Admittedly, the syntax looks awful. Indeed, some explanation is necessary.
First, the top-level stuff
says _ArraySizeHelper is a function that returns a reference (note the &) to a char array of N elements.
Next, the function parameter is
which is a reference to a T array of N elements.
Finally, countof is defined as the size of the result of the function _ArraySizeHelper . Note we don’t even need to define _ArraySizeHelper() , — a declaration is enough.
With this new definition,
becomes valid, just as we desire.
Am I happy now? Well, I think this definition is definitely better than the others we have visited, but it is still not quite what I want. For one thing, it doesn’t work with types defined inside a function. That’s because the template function _ArraySizeHelper expects a type that is accessible in the global scope.
Find Array Length in C++

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Introduction
In this article, we are going to learn about the various ways following which we can find array length in C++.
Basically, when we say the length of an array actually we refer to the total number of elements present in the corresponding array. For example, for an array as given below:
The size of the array or length of the array here is equal to the total number of elements in it. Which, in this case, is ‘5’.
Ways to find Length of an Array in C++
Now let us take a look at the different ways following which we can find the length of an array in C++, they are as follow:
- Counting element-by-element,
- begin() and end() ,
- sizeof() function,
- size() function in STL,
- Pointers.
Now, let us discuss each method one-by-one with examples and in detail.
1. Counting element-by-element
Traversing throughout the given array and simultaneously counting the total number of elements we traversed can give us the length of the array right?
But for traversing we cannot use a for loop directly if we do not know the array length beforehand. This issue can be solved by using a simple for-each loop. Look at the code below carefully.
Output:
Here, as we said, we traverse through the entire array arr using a for-each loop with iterator i. Simultaneously the counter, c is incremented. At last, when the traversing is over, c holds the length of the given array.
2. Using begin() and end()
We can also calculate the length of an array using the standard library’s begin() and end() functions. The two functions return iterators pointing to the start and the end of the corresponding array respectively. Take a close look at the given code,
Output:
Hence, here as we can see, the difference between the return values of the two functions end() and begin() give us the size or length of the given array, arr . That is, in our case, 4.
3. Using sizeof() function to Find Array Length in C++
The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too. Hence, if we simply divide the size of the array by the size acquired by each element of the same, we can get the total number of elements present in the array.
Let us how that works
Output:
As we can see, we get our desired output.
4. Using the size() function in STL
We have the size() function defined in the standard library which returns the number of elements in the given container(array in our case).
Output:
As desired, we get the output as shown above.
5. Using Pointers to Find Array Length in C++
We can also find the length of a given array using pointers. Let us see how
Output:
The expression *(arr+1) gives us the address of the memory space just after the array’s last element. Hence, the difference between it and the arrays starting location or the base address(arr) gives us the total number of elements present in the given array.
Conclusion
So, in this tutorial, we discussed the various methods to find array length in C++. Even though each one of the above examples is easy to go with, we prefer the one using the for-each loop. Not only because of code readability but also for its cross-platform reliability.
For any further questions feel free to use the comments below.
References
-
— Stack Overflow question, — JournalDev post.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Как определить длину массива в C++
По сути, когда мы говорим о длине массива, мы имеем в виду общее количество элементов, присутствующих в соответствующем массиве. Например, посмотрите на массив ниже:
Размер (или длина) массива равна общему количеству элементов в нем. Следовательно, в данном случае это «5».
Способы определения длины массива в C++
Теперь давайте посмотрим на различные способы, с помощью которых мы можем выяснить длину массива в C++:
- поэлементный подсчет,
- begin() и end(),
- функция sizeof(),
- функция size() в STL,
- указатели.
Теперь давайте обсудим каждый метод подробно и с примерами.
1: Поэлементный подсчет
Самый очевидный способ – перебрать заданный массив и одновременно подсчитать общее количество перебранных элементов.
Но если мы заранее не знаем длину массива для итерации, то в таком случае мы не можем использовать цикл for. Эту проблему можно решить, используя простой цикл for-each. Внимательно посмотрите на приведенный ниже код.
Вы получите такой результат:
Как мы говорили выше, здесь мы перебираем весь массив arr, используя цикл for-each с итератором i. Значение счетчика c увеличивается по мере итерации. Когда перебор закончится, в c вы найдете длину данного массива.
2: Функции begin() и end()
Мы также можем вычислить длину массива, используя стандартные функции begin() и end(). Эти две функции возвращают итераторы, указывающие на начало и конец массива соответственно. Внимательно посмотрите на данный код:
Следовательно, разница между возвращаемыми значениями двух функций end() и begin() дает нам размер или длину данного массива. Данный код вернет:
3: Функция sizeof()
Оператор sizeof() в C++ возвращает размер переданной переменной или данных в байтах. Кроме того, он возвращает общее количество байтов, необходимых для хранения массива. Следовательно, если мы просто разделим размер массива на размер, занимаемый каждым его элементом, мы узнаем общее количество элементов, присутствующих в массиве.
Давайте посмотрим, как это работает:
В результате мы получим:
4: Функция size() в STL
В стандартной библиотеке есть функция size(), которая возвращает количество элементов в заданном контейнере (в нашем случае это массив).
В результате вы получите:
5: Определение длины массива с помощью указателей
Узнать длину массива можно с помощью указателей. Давайте посмотрим, как это делается:
В результате мы получим:
Выражение *(arr+1) выдает адрес области памяти сразу после последнего элемента массива. Следовательно, разница между ним и начальным местоположением массива (или базовым адресом, arr) показывает общее количество элементов, присутствующих в данном массиве.
Заключение
Итак, в этом мануале мы обсудили различные методы определения длины массива в C++. Все приведенные выше методы просты в использовании, однако мы предпочитаем применять цикл for-each – не только из-за удобочитаемости кода, но и из-за его кросс-платформенной надежности.