简体   繁体   English

是否有可能将指针作为std :: vector中的连续内存片段 <char> 在C ++中?

[英]Is it possible to get the pointer the continous memory fragment in a std::vector<char> in C++?

I moved my code to use std::vector<char> instead of char *mem = malloc(...) but now I am facing a problem that I can only access the vector data through operator [] but not via a pointer. 我移动我的代码使用std::vector<char>而不是char *mem = malloc(...)但现在我遇到的问题是我只能通过operator []访问矢量数据,而不是通过指针访问。

I can't write stuff like: 我不能写像这样的东西:

std::vector<char> data;
fill_data(data);
char *ptr = data;

Before I could do this: 在我这样做之前:

char *data = malloc(100);
fill_data2(data);
char *ptr = data;

Any ideas if it's still possible to access data in a vector via pointer? 如果仍然可以通过指针访问vector数据,是否有任何想法?

Thanks, Boda Cydo. 谢谢,Boda Cydo。

访问矢量数据的标准方法是使用

&data[0]

Of course. 当然。 The vector was designed for this purpose: 该载体是为此目的而设计的:

char * p = &(myVector[0]) ;

And now, p points to the first item in the vector, and you can access each item by playing with the pointer, as you would in C. 现在,p指向向量中的第一个项目,您可以通过使用指针来访问每个项目,就像在C中一样。

You can write that code perfectly legally. 您可以完全合法地编写该代码。 All you need to do is alter fill_data to take a std::vector<T>& . 您需要做的就是改变fill_data以获取std::vector<T>& Of course, if this is an external C API, then you don't have much choice in the matter. 当然,如果这是一个外部C API,那么你在这个问题上没有太多选择。

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

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