如何正确地将 char ** x 转换为 const char **

Vim*_*tel 3 c++ gcc-warning

我有以下变量。

char **arr

然后我想对数组进行一些修改,这意味着它不能被声明为常量。

现在我有一个接受 type 参数的函数const char ** arr。但是我无法控制这个函数的签名。

现在,当我转换arrconst char ** arrg++ 时会生成一个警告,即[-Werror=cast-qual].

有关更多说明,请考虑以下 MCVE:

#include<cstdio>

void print(const char** x){
    printf("%s", x[0]);
}

int main(int argc, char **argv){
    if(argc>1){
        print((const char **)argv);     
    }
     return 0;
}

//Then compile it as follow:

$ g++ -Wcast-qual test.cpp

//gives the following output:

MCVE.cpp: In function ‘int main(int, char**)’:
MCVE.cpp:5:36: warning: cast from type ‘char**’ to type ‘const char**’ casts away qualifiers [-Wcast-qual]
   const char ** q = (const char**) argv;

Run Code Online (Sandbox Code Playgroud)

所以我的问题是为什么这会产生警告?这样做有什么风险吗?

以及如何实现我想要实现的行为?

R S*_*ahu 7

允许从char**toconst char**进行强制转换为修改 aconst char或 a提供了一个漏洞const char*

示例代码:

const char c = 'A';

void foo(const char** ptr)
{
   *ptr = &c; // Perfectly legal.
}

int main()
{
   char* ptr = nullptr;
   foo(&ptr);  // When the function returns, ptr points to c, which is a const object.
   *ptr = 'B'; // We have now modified c, which was meant to be a const object.
}
Run Code Online (Sandbox Code Playgroud)

因此,将 a char**to 转换const char**为不是安全的转换。


您可以使用

if(argc>1)
{
   const char* ptr = argv[0];
   print(&ptr);     
}
Run Code Online (Sandbox Code Playgroud)

让您的代码在没有cast-qual警告的情况下编译。

如果您需要传递的不仅仅是第一个参数,则需要构造一个数组const char*并使用它。

if(argc>1)
{
   int N = <COMPUTE N FIRST>;
   const char** ptr = new const char*[N];
   for (int i = 0; i < N; ++i )
   {
      ptr[i] = argv[i];
   }

   print(ptr);

   delete [] ptr; // Make sure to deallocate dynamically allocated memory.
}
Run Code Online (Sandbox Code Playgroud)