如何将const char **路径指定为字符串?

时间:2014-11-18 22:41:20

标签: c++ macos

我想在运行时获取OS X的工作可执行文件目录。我在下面找到了这段代码,但我不知道如何将const path用作字符串。它抱怨说:

testingtesting.cxx:7:30: warning: format specifies type 'char *' but the
  argument has type 'const char **' [-Wformat]
printf("path is : %s\n", path);

我想将const char **路径指定为字符串。以下是代码:

#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

int main (int argc, const char *argv[], const char *env[], const char *path[]) {
  // path[0] now contains the path to the executable
  // NOT PORTABLE! OS X ONLY!

    std::string s = path.c_str();

    printf("path is : %s\n", s);
  return 0;
}

1 个答案:

答案 0 :(得分:3)

变化:

std::string s = path.c_str();

printf("path is : %s\n", s);

为:

std::string s(path[0]); // create C++ std::string and initialise
                        // from C string `path[0]`

std::cout << "path is : " << s << std::endl;