简体   繁体   English

如何创建一个指向字节数组的指针?

[英]How to create a pointer to a byte array?

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? 那么,如何完成呢?

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] . (需要C ++ 11。)您可以使用&test[0]获得指向字节的指针。

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

Now you have test.data() as your pointer. 现在,您将test.data()用作指针。 Oh, and now you have automatic memory management as well. 哦,现在您还具有自动内存管理功能。 And size() . size() And begin() and end() . 以及begin()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): 这是使用C ++ 17 std::byte类型的版本(应使用-std=c++17编译器标志):

#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. 对于堆分配,最好使用具有统一初始化的 std::vector ,正如其他人已经指出的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM