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

3
我想创建一个指向新字节数组的指针,并希望可以一次性初始化它。
例如,这可以用于空字节数组:
byte *test = new byte[10];

但是我如何一次性创建指向字节数组的指针并初始化它呢?
byte *test = new byte {0x00, 0x01, 0x02, 0x03};

...不过它不起作用。

那么它究竟是如何完成的呢?


我对C++一无所知(因此这是一个注释),但在其他几种语言中,它将类似于new byte[] {...}(注意[])。 - njzk2
考虑使用 byte test[] = {0x00, 0x01, 0x02, 0x03};,如果需要其地址,则使用 &test。如果数组是静态的,则无需手动管理内存。 - Red Alert
@RedAlert 在C++中几乎从不需要手动管理内存。 - user1804599
4个回答

1

不要动态创建数组,考虑使用向量代替:

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

(需要C++11)您可以通过使用&test[0]来获取指向字节的指针。


一个在windows 10上编译的程序,使用vector时在XP上运行结果不可靠。这是为什么?std::vector在XP上没有实现吗? - majidarif

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

现在你有test.data()作为指针。哦,现在你也有自动内存管理了。还有size()。以及begin()end()。哦,还有异常安全性。

0
以下是使用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;
}

-2
如果您的数组在堆栈上,您可以这样做:
// 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;

对于堆分配,建议使用具有统一初始化std::vector,就像其他人已经提到的那样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接