Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

float vector and pointer returns different values even though they have same adress

I have a class which returns vector<vector<float>> with its getTemplates() function. My code is as follows for this case:

cout << "Get [0][0] " << s.getTemplates()[0][0] << endl;
cout << "vec addr " <<  &(s.getTemplates()[0][0]) << endl;

float *embFloat = s.getTemplates()[0].data();
cout << "embFloat: " << embFloat << endl;
cout << "*embFloat " << *embFloat << endl;
cout << "embFloat[0] " << embFloat[0] << endl;

and the output is as follows:

Get [0][0] 0.00191223
vec addr 0x555557973280
embFloat: 0x555557973280
*embFloat -8.71571e+33
embFloat[0] -8.71571e+33

I expect embFloat[0] and s.getTemplates()[0][0] to return exactly same value. What am I missing here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

s.getTemplates() returns a temporary which goes out of scope at the end of the statement that contains it.

float *embFloat is therefore a dangling pointer – i.e. it’s pointing to an object that has been destroyed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading