简体   繁体   English

函数参数,const char **,临时变量

[英]Function argument, const char **, Temp Variable

I want to pass an argument to a function, which takes a const char ** 我想将参数传递给需要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 . 这段代码可以正常工作,但是我不想遍历临时变量tempC I want to pass testString.c_str() directly. 我想直接传递testString.c_str() 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. 是否可以在不使用temp变量的情况下做到这一点。

I want to pass testString.c_str() directly. 我想直接传递testString.c_str()。

You can't. 你不能 std::string::c_str() returns a const char * . std :: string :: c_str()返回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: 通常,采用const char **函数这样做有两个原因:

1: It takes an array of strings. 1:需要一个字符串数组。 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. 通常,采用数组的C样式函数需要第二个参数,该参数说明数组中有多少个元素。 I hope you're putting a 1 in there. 希望您在其中输入1。

2: It is returning a string. 2:正在返回字符串。 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. 您应该创建一个const char *作为变量,将其初始化为NULL,然后将指针传递给它作为参数。 It's value will be filled in by the function. 它的值将由函数填充。

You're going to need two temp variables to call glShaderSource, so you might as well wrap them up in one function that takes the string directly. 您将需要两个临时变量来调用glShaderSource,因此您最好将它们包装在一个直接采用字符串的函数中。

#include <gl.h>
#include <string>

void setShaderFromString(std::string &instr, GLuint shader)
{
        const GLchar *str[1]; // room for one const GLchar *
        GLint   len[1];       // make this an array, for symmetry

        str[0] = instr.c_str();
        len[0] = instr.length();
        glShaderSource(shader, 1, str, len);

}

Simply - no. 简单-不。

(filling up some space) (填满一些空间)

You can also do type-casting: 您还可以进行类型转换:

int main()
{
    testFunc((const char **)&testString);
    return 0;
}

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

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