简体   繁体   English

如何在c ++中创建'char * []'?

[英]How to create 'char *[]' in c++?

I am trying to call into a C library from C++. 我试图从C ++调用C库。 The interface requires char* [] . 该接口需要char* [] The compilation fails if I pass const char * [] . 如果我传递const char * [] ,编译将失败。

How do I safely create one of these? 我如何安全地创建其中一个? This is the best I can do, but I don't know if it's even correct. 这是我能做的最好的,但我不知道它是否正确。 I'm creating the array with 1 c-string in it only. 我正在创建仅包含1个c-string的数组。

string attr = "memberUid";
vector<char> attr_v(attr.begin(), attr.end());
attr_v.push_back('\0');
char * attrs[] = {&attr_v[0]};

I do not want to trigger the deprecated conversion warning, ie the one that fires with the following: 我不想触发已弃用的转换警告,即使用以下内容触发的警告:

char * attr = "memberUid";

Assuming you have a vector of strings ( std::vector<std::string> ), which I'll call source : 假设你有一个字符串向量( std::vector<std::string> ),我将其称为source

std::vector<char*> asArgument( source.size() );
std::transform(
    source.begin(), source.end(),
    asArgument.begin(),
    []( std::string const& elem ) { return const_cast<char*>( elem.c_str() ); } );
cFunction( asArgument.data(), asArgument.size() );

If you need the array of char* to be NULL terminated, just create asArgument with source.size() + 1 . 如果需要将char*数组作为NULL终止,只需使用source.size() + 1创建asArgument

Of course, if you need string literals: 当然,如果你需要字符串文字:

char const* asArgument[] = { ... };

will do the trick, with a const_cast at the call site ( const_cast<char**>( asArgument ) ). 就可以了,具有const_cast在调用位置( const_cast<char**>( asArgument )

This assumes that the called function doesn't actually try to modify anything; 这假设被调用的函数实际上并没有尝试修改任何东西; that the absence of const is only because it is legacy code. 缺少const只是因为它是遗留代码。 If it does modify any of the strings passed to it, you'll have to make deep copies. 如果它确实修改了传递给它的任何字符串,则必须进行深层复制。

hope this will help , for loop is need to init the whole array 希望这会有所帮助,因为循环需要初始化整个数组

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
  vector<string> attr_v;
  attr_v.push_back("10");
  char * attr[100];
  attr[0]= const_cast<char*>(attr_v[0].c_str()); 
   return 0;
}

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

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