-1

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?

Ouss
  • 11
  • 1
  • 2

3 Answers3

1

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.

SubSevn
  • 1,008
  • 2
  • 10
  • 27
1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

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());
Jarod42
  • 203,559
  • 14
  • 181
  • 302