Search code examples
c++classsizeof

Getting sizeof a member of the class in C++


I've built a class called IntSet. My problem is that i dont want to storage another element that is the maximum amount of elements i want to introduce in elem array. So, in add method or any other method, i want to find out the max size i've allocated in the IntSet (int dim_max) constructor using this operation :

int n = sizeof(elem) / sizeof(*elem); //or sizeof(elem) / sizeof(int);
cout << "N is = " << n;

However, this doesnt work, everytime n is 1, even if i allocate elem = new int[dim_max];, where dim_max is a variable i read from the keyboard and it's much bigger than 1. Here is the code :

 #include <iostream>
using namespace std;

class IntSet{
    int *elem;
    int dim;

    public:

    IntSet (int dim_max) {
        dim = -1;
        elem = new int[dim_max];
    }

     void add(int new_el) {
        int n = sizeof(elem) / sizeof(int);
        cout << "N is =" << n;
        for(int i = 0; i < n; i++) {
            if(elem[i] == new_el) {
                cout << "It's already there !";
                return;
            }
        }
        dim++;
        if(dim == n) {
            elem = (int*)realloc(elem, sizeof(int) * (n + 1));
            global_var++;
        }
        elem[dim] = new_el;
     }
};

Solution

  • The sizeof operator works on the types at compile time. Since elem is an int*, sizeof(elem) is the same as sizeof(int*). And *elem is an int, so sizeof(*elem) is sizeof(int).

    So in the end, your formula is equivalent to sizeof(int*)/sizeof(int), regardless of what you put in elem. There is no standard way to find out the number of elements of the array that that was allocated for a pointer.

    For your purpose, you either must either keep track of dim_max in your class, or, better, replace the use of pointers and arrays with the nicer vector.

    Vectors offer a size() function, and allow to easily add new element dynamically at the end using push_back(). Maybe it could interest you as well: there is also a set container in the standard library.