2

我想用 C++ 写一个指向文件的动态指针。

这是我在头文件中的声明:

byte* buffer;

然后在 Cpp 文件中,我分配了它:

buffer = new byte[1000];

但是,在动态分配中大小将大于 1000。

然后我写入文件:

我的文件流;

myfile.open("test.txt", ios::binary);
myfile.write((char*)buffer, 1000);  
myfile.close();

如果我将缓冲区的长度指定为 1000,那么 1000 之后的其余字节将被丢弃。如果我使用: sizeof(buffer) 那么它只写入 1 个字节。

如何获取缓冲区的动态大小?

4

2 回答 2

11

Simple:

std::vector<byte> buffer;
buffer.resize(1000);
myfile.write(&buffer[0], buffer.size());
于 2012-05-22T09:31:39.217 回答
0

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.

于 2012-05-22T09:34:28.043 回答