I am trying to call into a C library from C++. The interface requires char* []
. The compilation fails if I pass 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.
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<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
.
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 )
).
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. 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.