C++ 如何将 vector<unsigned char> 转换为 char*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4254615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:56:06  来源:igfitidea点击:

How to cast vector<unsigned char> to char*

c++

提问by Richard Knop

I have a buffer like this:

我有一个这样的缓冲区:

vector<unsigned char> buf

How can I cast it to char*?

如何将其转换为 char*?

If I do:

如果我做:

(char *)buf

I get this error:

我收到此错误:

/home/richard/Desktop/richard/client/src/main.cc:102: error: invalid cast from type ‘std::vector<unsigned char, std::allocator<unsigned char> >' to type ‘char*'

For those wondering why I am trying to do this. I need to pass the buffer to this function:

对于那些想知道我为什么要这样做的人。我需要将缓冲区传递给这个函数:

n_sent = sendto(sk,(char *)buf,(int)size,0,(struct sockaddr*) &server,sizeof(server));

And it only accepts char*.

它只接受 char*。

回答by Armen Tsirunyan

reinterpret_cast<char*> (&buf[0]);

The vector guarantees that its elements occupy contiguous memory. So the "data" you seek is actually the address of the first element (beware of vector <bool>, this trick will fail with it). Also, why isn't your buffer vector<char>so that you don't need to reinterpret_cast?

该向量保证其元素占用连续的内存。所以你寻找的“数据”实际上是第一个元素的地址(当心vector <bool>,这个技巧会失败)。另外,为什么不是您的缓冲区,vector<char>以便您不需要 reinterpret_cast?

Update for C++11

C++11 更新

reinterpret_cast<char*>(buf.data());

回答by ronag

reinterpret_cast<char*>(buf.data());

回答by Chris Lutz

Try

尝试

(char *)(&buf[0])

or another, more C++ cast. But also tell us what you're using this for. It may be a bad idea.

或另一个,更多的 C++ 演员。但也请告诉我们您使用它的目的。这可能是个坏主意。

回答by Ben Hymanson

It's very unlikely that you want to cast vector<unsigned char>to unsigned char *, but you can get a a valid pointer like this:

您不太可能想要强制转换vector<unsigned char>unsigned char *,但是您可以获得这样的有效指针:

vector<unsigned char> v;
unsigned char *p = &*v.begin();

That strange expression will give you the pointer to the start of the internalallocated array created by the vector. If you modify the vector at all it may no longer be valid.

这个奇怪的表达式会给你一个指向向量创建的内部分配数组的开始的指针。如果您完全修改向量,它可能不再有效。

The reason for the redundant looking &*is that the *is really operator *on the iterator returned by v.begin(). That returns a reference to the first char of the array which you can then take the address of with &.

看起来多余的原因&**is 确实operator *在由 返回的迭代器上v.begin()。这将返回对数组第一个字符的引用,然后您可以获取 with 的地址&