Reputation: 20644
I want to write a dynamic pointer to a file in C++.
This is my declaration in header file:
byte* buffer;
Then in Cpp file, I allocated it:
buffer = new byte[1000];
However the size will be bigger than 1000 in dynamic allocation.
Then I write to the file:
ofstream myfile;
myfile.open("test.txt", ios::binary);
myfile.write((char*)buffer, 1000);
myfile.close();
If I specify the length of buffer to 1000, then the rest of bytes after 1000 will be discarded. If I use: sizeof(buffer) then it is only 1 byte written.
How can I get the dynamic size of the buffer?
Upvotes: 2
Views: 1545
Reputation: 19445
The size of the buffer is 1000. It's true that when you use "new" it sometimes can allocate more memory but this is done in order to fasten the next "new". so every other memory that was allocated after the 1000 first bytes may and probably will be used in future "new"s.
bottom line you can't and should assume you have any more then 1000 bytes.
Upvotes: 0
Reputation: 179867
Simple:
std::vector<byte> buffer;
buffer.resize(1000);
myfile.write(&buffer[0], buffer.size());
Upvotes: 11