2

I am trying to convert a char pointer to a string pointer but I am not sure if I am doing it correctly. I just wanted to post what I was trying and see if it was correct.

For context, I have a char * called ent->d_name and I need that to become a string *. This is what I have been doing:

std::string arg = std::string(ent->d_name); std::string * arg_p = &arg; Command::_currentCommand->insertArgument(arg_p); 

The insert command function takes a string pointer.

11
  • 7
    There is rarely any reason to use a string *. If you are using a library that does so, the person who designed the library almost certainly didn't know what they were doing, and you should not be using that library. And you cannot directly convert a char * to a string *. Commented Oct 21, 2018 at 22:07
  • It is for my school project. I do not like it either, but I do not have a choice. Commented Oct 21, 2018 at 22:08
  • Whether this is correct or not depends on what this Command thingie is going to do with arg_p. Does it just use it right away or does it store it somewhere? Is it guaranteed that arg does not get destroyed before the Command accesses the pointer you gave it? Commented Oct 21, 2018 at 22:14
  • You should probably take a step back and explain why you think you need a string*. It's more likely you want a string, and probably want to create a new one instead fo casting... Commented Oct 21, 2018 at 22:16
  • 1
    @Darren This is what I have been doing: -- Even if you were doing that, there is no need for the pointer. std::string arg = std::string(ent->d_name); Command::_currentCommand->insertArgument(&arg); -- Why the intermediate pointer variable, when you could have just passed the address of arg? Commented Oct 21, 2018 at 23:13

1 Answer 1

1

You could use

std::string *arg_p = new std::string(ent->d_name); 

It will create a memory leak unless you delete each string after use, but apart from that it will work.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.