size of array

The function m.size() works only if i declare array as say array<int,5> m, but not with int m[5]. Why is that?

The code below doesn't work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <array>

using namespace std;

int main()

{
	int mm[4] = { 1, 2, 3, 4 };

	cout << mm.size() << endl;


}
because c-style arrays are not classes. They are primitive types and do not have members. Avoid them.
There is way to know size of array, but it is dangerous because arrays are easily decays into pointers. There is no way to know size of dynamic array.

best way is something like:
1
2
3
4
5
6
int main()
{
    const int arr_size = 4; //Use constant instead of magic number
    int mm[arr_size] {1, 2, 3, 4, };
    std::cout << arr_size << std::endl;
}
Last edited on
Thanks. I was just wondering how I can get the size of an array that has been dynamically manipulated and changed. In Wolfram Mathematica it's just Length[m].

Any ideas?
Use std::vector. It is more useful than c-style dynamic array and way more safer.

Only other way is to store array size in separate variable.
Thanks.
One more thing: how can I put a control so that if I am inputting integers it goes on to accept and so some stuff, but when I input a letter or word loop breaks? Is there a way to do it with "while" loop?
you mean something like
1
2
3
4
5
6
int number;
int counter = 0;
while(std::cin >> number) {
    ++counter;
}
std::cout << "You have entered " << counter << " numbers";
But that just counts the numbers. I need to break the loop when i enter say letter "x" instead of an integer.
You can do anything instead of just counting. Loop will be broken when you enter anything non-integer.
I see, thanks.
Topic archived. No new replies allowed.