Question

i would like to create a pointer to a new byte array and i want to initialize it at once.

For example this could be used for an empty byte array:

byte *test = new byte[10];

but how can i create the pointer to the byte array and initialize it at once?

byte *test = new byte {0x00, 0x01, 0x02, 0x03};

...doesnt work though.

So how is it done anyway?

Was it helpful?

Solution

Rather than creating arrays dynamically, consider creating vectors instead:

std::vector<byte> test{0x00, 0x01, 0x02, 0x03};

(Requires C++11.) You can get at a pointer to the bytes by using &test[0].

OTHER TIPS

std::vector<byte> test{ 0x00, 0x01, 0x02, 0x03 };

Now you have test.data() as your pointer. Oh, and now you have automatic memory management as well. And size(). And begin() and end(). Oh and also exception safety.

Here's a version using the C++17 std::byte type (the -std=c++17 compiler flag should be used):

#include <vector>
#include <cstddef>
#include <iostream>

template <typename ...Args>
std::vector<std::byte> init_byte_vector(Args&& ...args){
    return std::vector<std::byte>{static_cast<std::byte>(args)...};
}

int main(void)
{
    auto v = init_byte_vector(0x00, 0x01, 0x02, 0x03);
    auto v_ptr = v.data();
    ...
    return 0;
}

If your array is on the stack, you could do:

// Assume byte is typedef'd to an actual type
byte test[10]={0x00, 0x01, 0x02, 0x03}; // The remainder of the bytes will be
                                        // initialized with 0x00

// Now use test directly, or you can create a pointer to point to the data
byte *p=test;

For heap allocations, prefer std::vector with uniform initialization as others have already stated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top