user3397612
user3397612

Reputation: 91

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?

Upvotes: 1

Views: 161

Answers (2)

Rupesh Yadav.
Rupesh Yadav.

Reputation: 904

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).

Upvotes: 2

ravi
ravi

Reputation: 10733

It will always return same value what you have specified when creating array. You have to maintain a seperate variable ( let's say "count" ) to keep track of how many elements are there in array.

Upvotes: 1

Related Questions