why array is smaller than matrix smaller than vector ? c++

142 views Asked by At

I am trying to read the mnist file and put the elements in a vector of matrix. code to read mnist

for(int r = 0; r < n_rows; ++r)
{
    for(int c = 0; c < n_cols; ++c)
    {
        unsigned char temp = 0;
        file.read((char*)&temp, sizeof(temp));
        data[r][c] = temp;
        //std::cout << "r: " << r << " c: " << c << " temp: "<< sizeof(temp) << "\n";
    }
} //this print my array the correct way

for(int k = 0; k < 28; k++)
{
    for(int z = 0; z < 28; z++)
    {
        std::cout << data[k][z] << " ";
        if(z == 27)
            std::cout << "\n";
    }
}

cv::Mat img(28,28,CV_8U,&data);
mnist.push_back(img);
std::cout<<"data: "<< sizeof(data) << " img: "<< sizeof(img) << " mnist: " << sizeof(mnist) <<"\n";

the output of the last line above is :

data(array): 784 img(cv::Mat): 96 mnist(vector of matrix): 24

should they not be at least the same the same size ? this why i think when i print my matrix is not showing the right output (the same as the array) i guess the vector is referencing to the matrix and the matrix is referencing to the array but then something get changed in the memory somewhere and thats why the output is not what i expect ?

[edit]

the code above is in a function returning the vector of matrix.

When i use the code inside the main function the output is ok!

can someonw explain ?

I would prefer to have that in a seperate function instead of having a giant main... but ill keep working with whats working for now.

1

There are 1 answers

1
jwezorek On BEST ANSWER

Basically you are misunderstanding what sizeof does. It returns the size of an object's type but not the size of all the memory that is owned or referred to by an object. To be specific the size of a pointer is typically 8 bytes regardless of how much memory the pointer points to, e.g.

int main()
{
    int* foo;
    std::cout << "foo is " << sizeof(foo) << " bytes.\n";

    foo = new int[10000];
    std::cout << "foo is still " << sizeof(foo) << " bytes.\n";

}

The rest of the answer to your question follows from the above. For example, an std::vector is often sizeof 24 bytes because it is often implemented using three pointers.