简体   繁体   中英

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?

There is no way to find the length of a buffer given nothing but a pointer. If you are certain that it's a string you can use one of the string length functions, or you can keep track of the length of the buffer yourself.

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());

Pointer doesn't have a "length". What you need is the length of the array which the pointer points to.

No, you cannot extract that information from the pointer.

If the array contains a valid, null-terminated character string, then you can get the length of that string by iterating it until you find a null character which is what strlen does.

If not, then what you normally do is you store the length in a variable when you allocate the array. Which is one of the things that std::vector or std::string will do for you, whichever is more appropriate for your use.

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