user3397612 user3397612 - 3 months ago 7
C++ Question

Finding the size of an array in C++

Normally, I would find the size of the double array by using

int size = sizeof(array_name)/sizeof(double)


However, I am using the double array named "grades" as a member in a class called "Grades"

class Grades{
private:
double grades[1024];

public: Grades(string gradeList);
Grades();

int getNumGrades();
string toString();
};


The double array is later filled in the constructor. However, when I do

cout << "size = " << (sizeof(grades)/sizeof(double)) << endl;


It ALWAYS gives me 1024. This is at the end of the constructor after it has filled some random values. I filled it with 5 values. How can I make this return the number of filled elements?

Answer

I think you should have one other member called elemInArray, and it could be implemented in this way.

class Grades{
    private:
        double grades[1024];
        unsigned int elemInArray;   // Note this

    public: Grades(string gradeList);
            Grades();

            int getNumGrades();
            string toString();
};

And whenever you insert the elements or remove elements from that array, you can increment and decrement elemInArray to keep track of the number of elements in the array.

Otherwise use STL containers (http://en.cppreference.com/w/cpp/container).

Comments