My C++ program needs a block of uninitialized memory and a void*
pointer to that block so that I can give it to a third party library. I want to pass control of
Use new
with a single object and new[]
with an array of objects. So, for example:
int* x = new int; // Allocates single int int* y = new int[5]; // Allocates an array of integers *x = 10; // Assignment to single value y[0] = 8; // Assignment to element of the array
If all you are doing is allocating a memory buffer, then allocate an array of char
as in:
int bufferlen = /* choose a buffer size somehow */ char* buffer = new char[bufferlen]; // now can refer to buffer[0] ... buffer[bufferlen-1]
However, in C++, you should really use std::vector
for arbitrary arrays, and you should use std::string
for character arrays that are to be interpreted or used as strings.
There is no reason to invoke ::operator new
or ::operator new[]
explicitly rather than using the ordinary syntax for these calls. For POD and primitive types (e.g. char
) no initialization will take place. If you need to get a void*
buffer, then simply use static_cast
to convert char*
to void*
.