stcheng
stcheng

Reputation: 141

How to convert from a string array to a char array array?

I want to pass an array of arguments to exec() function. The current parameters are all strings. How could I convert the array of string into the array of char array?

Right now I'm using const_cast to remove the const. The code does not look nice. Is there a better solution?

Sample code looks like:

void f(const string &dev, const string &status){

  char* args[] = {"link", "set", "dev", const_cast<char*>(dev.c_str()), 
  const_cast<char*>(status.c_str())};
  execv("/sbin/ip", args);
}

Upvotes: 0

Views: 78

Answers (2)

Justin
Justin

Reputation: 25337

It's probably best to declare args as an array of char const*:

char const* args[] = {"link", "set", "dev", dev.c_str(), status.c_str()};

However, if you truly need a char* and not a char const*, as execv requires, we need std::string::data:

void f(const string &dev_, const string &status_){
  // Note: string literals don't convert to char* in C++,
  // although some compilers allow it as an extension.

  // Declare these as arrays so we can form `char*`s to them:
  char link[] = "link";
  char set[] = "set";
  char dev_lit[] = "dev";

  // No choice but to copy the const args:
  std::string dev{dev_};
  std::string status{status_};

  // C++17-specific:
  char* args[] = {link, set, dev_lit, dev.data(), status.data()};
  execv("/sbin/ip", args);
}

Before C++17, you can use &status[0] rather than status.data(), which is correct even if status.size() == 0.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206687

The code does not look nice. Is there a better solution?

For what it's worth, use of

char* args[] = {"link", "set", "dev", ... };

is wrong to start with. String literals can decay to char const*, not char*.

I suggest use of a helper function that uses strdup to give you a copy of the input string.

char* toArg(std::string const& s)
{
    return strdup(s.c_str());
}

and use

char* args[] = {toArg("link"), toArg("set"), toArg("dev"), toArg(dev), toArg(status)};

Upvotes: 0

Related Questions