Search code examples
c++qtfilebuffervariable-length

Want to know the length of a buffer C++


I am new to C++ and programming and I would like to know if there is a way to get the length of a pointer.
Let's say Myheader is a struct with different types of data inside.
My code goes like this:

char *pStartBuffer;
memcpy(pStartBuffer, &MyHeader, MyHeader.u32Size);

So I want to know the length of the buffer so that I can copy the data to a file using QT write function.

file.write(pStartBuffer, length(pStartBuffer));

How can I do this?


Solution

  • Pointers don't know its allocated size.

    You may use std::vector which keep track of size for you:

    std::vector<char> pStartBuffer(MyHeader.u32Size);
    memcpy(pStartBuffer, &MyHeader, MyHeader.u32Size);
    

    And latter:

    file.write(pStartBuffer.data(), pStartBuffer.size());