简体   繁体   中英

Different result from sizeof() from [] and .data()

const GLfloat tmpArray[] = { 
  -1.0f, -1.0f, 0.0f,
  1.0f, -1.0f, 0.0f,
  0.0f,  1.0f, 0.0f,
};
std::cerr << sizeof(tmpArray) << std::endl;

This gives a result of 36

std::vector<GLfloat> tmpVector { 
  -1.0f, -1.0f, 0.0f,
  1.0f, -1.0f, 0.0f,
  0.0f,  1.0f, 0.0f,
};
std::cerr << sizeof(tmpVector.data()) << std::endl;

While this gives a result of 8. I read here on SO that you can get an array out of a vector using the .data() function. But why does it yeild different results? How would I go about to make these sizes match?

sizeof(tmpArray) returns the size of the array as expected.

sizeof(tmpVector.data()) returns the size of what is returned by the data() method, which is a pointer ( GLfloat* ). On your 64bit platform, the size of a pointer is 8 bytes.

How would I go about to make these sizes match?

Consider using (tmpVector.size() * sizeof(FLfloat)) ...

     const GLfloat tmpArray[] = {
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f,  1.0f, 0.0f,
     };
     cerr << "\n  sizeof(tmpArray) :                    "
          << sizeof(tmpArray) << endl;

     vector<GLfloat> tmpVector {
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f,  1.0f, 0.0f,
     };
     cerr << "\n  sizeof(tmpVector.data())               "
          << sizeof(tmpVector.data()) << endl;

     cerr << "\n  tmpVector.size() * sizeof(GLfloat) :  "
          << tmpVector.size() * sizeof(GLfloat) << endl;

With output:

sizeof(tmpArray) :                    36

sizeof(tmpVector.data())               8

tmpVector.size() * sizeof(GLfloat) :  36

The vector elements are stored contiguously, just like the array elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM