3

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?

3
  • I have no knowledge whatsoever about C++ (hence this being a comment), but in several other languages, it would be something like new byte[] {...} (note the [])
    – njzk2
    May 6, 2014 at 18:43
  • consider using byte test[] = {0x00, 0x01, 0x02, 0x03};, then using &test if you need its address. There's no need to manually manage memory if the array is static.
    – Red Alert
    May 6, 2014 at 18:45
  • @RedAlert there is almost never need to manually manage memory in C++.
    – user1804599
    May 6, 2014 at 18:46

4 Answers 4

1

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].

1
  • A program compiled on windows 10 that uses vector gives unreliable results when executed on XP. Why is that? Is std::vector not implemented on XP?
    – majidarif
    Aug 13, 2017 at 11:25
0
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.

0

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;
}
-2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.