I want to pass an argument to a function, which takes a const char **
#include<iostream>
using namespace std;
void testFunc(const char **test){}
string testString = "This is a test string";
int main()
{
const char *tempC = testString.c_str();
testFunc(&tempC);
return 0;
}
This code works fine, But I dont want to go through the temporary variable tempC. I want to pass testString.c_str() directly. Like the following,
int main()
{
testFunc(&testString.c_str());
return 0;
}
But, it shows error,
error C2102: '&' requires l-value
Is it possible to do it without using the temp variable.
You can’t. std::string::c_str() returns a
const char *. In order to make a pointer to a string, you have to put it in a variable and take its address.That being said, I’m far more concerned about what function you’re trying to pass this to. In general, a function that takes a
const char **does so for two reasons:1: It takes an array of strings. You are passing a single string. Usually, C-style functions that take an array need a second parameter that says how many elements are in the array. I hope you’re putting a 1 in there.
2: It is returning a string. In which case what you’re doing is not helpful at all. You should create a
const char *as a variable, initialize it to NULL, and then pass a pointer to it as the parameter. It’s value will be filled in by the function.