How to convert string to char *?

2

I wanted to ask about how to convert a string to a char *, the case is the one shown below, where I have a defined string and I want to name the variable x using .setName (), but it receives a char *, so that I can not simply place variable names for the string as an argument to the .setName () (the for cycle was the idea). Any ideas on how to put a string in .setName () as an argument? Or maybe not define it as string?

    IloNumVarArray x;
    string nombresvariables[12] = {"x11","x21","x31","x41","x12","x22","x32","x42","x13","x23","x33","x43"};

    for (int i = 0; i < 12; i++) {      
    x[i].setName(); //numero de variables
    }

    //x[0].setName("x11"); evitar tener que hacer esto
    //x[1].setName("x21");
    //x[2].setName("x31");
    //x[3].setName("x41");
    //x[4].setName("x12");
    //x[5].setName("x22");
    //x[6].setName("x32");
    //x[7].setName("x42");
    //x[8].setName("x13");
    //x[9].setName("x23");
    //x[10].setName("x33");
    //x[11].setName("x43");
    
asked by Alan 13.11.2018 в 18:32
source

3 answers

1

std::string has a c_str method that gives you direct access to its internal memory ... a pointer of type char:

char const* ptr = nombresvariables.c_str();

With this method you can make the direct call:

x[i].setName(nombresvariables[i].c_str());
    
answered by 14.11.2018 в 08:14
1

The std :: string class has the c_str () method that returns a pointer to the character buffer of the string.

Your code would be like this.

    for (int i = 0; i < 12; i++) {      
          x[i].setName(nombresvariables[i].c_str()); //numero de variables
    }

You have to be especially careful with this method, because when you return a pointer to its buffer if the object is destroyed you are left with a pointer that points to a memory area that you no longer use or use for something else.

An example of what you should not do would be the following.

char *puntero = NULL;
if(una condicion ...){
    string unacadena = "hola";
    puntero = unacadena.c_str();
}

...
printf("%s", puntero);

I would show you garbage, because the scope of a chain is inside the if.

So you can not do that, you can do it in the following way.

char *puntero = NULL;
if(una condicion ...){
    string unacadena = "hola";
    puntero = new char[unacadena.lentgh()];
    strcpy(puntero, unacadena.c_str());
}

...
if(puntero != NULL)
    delete puntero[];

You have information about the string class in the link link

    
answered by 14.11.2018 в 08:52
1

The class string has a method called c_str() which returns a char * with the content of the string. So you could rewrite your program in the following way:

IloNumVarArray x;

string nombresvariables[12] = {"x11","x21","x31","x41","x12","x22","x32","x42","x13","x23","x33","x43"};

for (int i = 0; i < 12; i++) {      
    x[i].setName(nombresvariables[i].c_str());
}
    
answered by 14.11.2018 в 21:05