-4

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.

110f716c
  • 100
  • 1
  • 2
  • 8
Pat cm pro
  • 75
  • 6
  • What is `data`? sizeof(object) is not object.size(). – 273K Aug 25 '21 at 15:46
  • 1
    Note that using `sizeof` on a vector will always give you the same size, no matter how many items are in the vector. This because the vector object just contains housekeeping information, and the actual data is stored in dynamically allocated memory. – Fred Larson Aug 25 '21 at 15:46
  • data is holding 28 * 28 uchar – Pat cm pro Aug 25 '21 at 15:48
  • 3
    [C++ sizeof Vector is 24?](https://stackoverflow.com/questions/34024805/c-sizeof-vector-is-24) – Drew Dormann Aug 25 '21 at 15:48

1 Answers1

1

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.

jwezorek
  • 8,592
  • 1
  • 29
  • 46
  • that is the right answer to my question for the thread. althought i made an edit after a couple of comments... – Pat cm pro Aug 25 '21 at 16:08