Home > Back-end >  converting char* to string* in C
converting char* to string* in C

Time:11-07

I have the following structure:

struct SimpleCommand {

  // Simple command is simply a vector of strings
  std::vector<std::string *> _arguments;

  SimpleCommand();
  ~SimpleCommand();
  void insertArgument( std::string * argument );
  void print();
};

I want to call the insertArgument function with an arguments of type char* that are given to me in an array, in a loop. If I call it with the following code:

for(i=0; i<n; i  ){
   insertArgument(array[i]);
}

it won't compile and gives me an

cannot convert ‘char*’ to ‘std::string*’

error. If I use the following code as suggested:

for(i=0; i<n; i  ){
   std:string s(array[i]);
   insertArgument(&s);
}

all the values in the vector point to the same string. How do I resolve this issue.

CodePudding user response:

For starters it is unclear why the function is declared like

void insertArgument( std::string * argument );

instead of

void insertArgument( const std::string &argument );

and correspondingly the vector should be declared like

std::vector<std::string> _arguments;

As for your question then instead of this for loop

for(i=0; i<n; i  ){
   std:string s(array[i]);
   insertArgument(&s);
}

you need to write

for(i=0; i<n; i  ){
   std:string *s = new std::string{ array[i] };
   insertArgument( s );
}

In this case the class is responsible to delete the memory allocated for strings when they will not be needed any more.

CodePudding user response:

You might store the string in a local variable:

char* cs;
std::string s(cs);
insertArgument(&s);

However, if you'd like to keep the strings, it's best if you store it in a std::vector<std::string> and take a std::string in insertArgument() (vs. std::string*).

  • Related