How to counting array size and total element in C++


Array in C++ is just same as variables that organized into one place. Basically, each element in array just stored sequentially in memory. To get the length of array, it just simple by get the size of array and divided it by the data type size. Since the way array stored the value sequentially, then it’s safe to doing this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;

int main() {
    int student[] = {1, 2, 3};

    // Showing size of student array
    cout << sizeof(student);
    cout << "n";
    // Showing the element by divided by the data type size
    cout << sizeof student / sizeof(int);
    return 0;
}

Thanks to +Jon Dubovsky that’s give another response that we should carefull of using this kind of approach. We change the “student” int array into int (not array), this code still works but showing wrong results. That’s mean silently fail.

We can passing into as function to make compiler see the declaration of variable. The problem is array is just the way of organizing variables into one reference. You can’t to pass it into method and doing size calculation on it.

In this is example, i use Template :

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

template<typename T, int size>
int countingArray(T(&)[size]){return size;}

int main() {
  int students[] = {1, 2, 3};
  cout << countingArray(students) << endl;

  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.