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

标签 c++ gcc-warning

我有以下变量。

char **arr

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

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

现在,当我将 arr 转换为 const char ** arr 时,g++ 会生成一个警告,即 [-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;


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

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

最佳答案

允许从 char**const char** 的转换提供了修改 const charconst 的漏洞字符*

示例代码:

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.
}

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


你可以使用

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

让您的代码在没有 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.
}

关于c++ - 如何正确地将 char ** x 转换为 const char **,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62649356/

相关文章:

c++ - C++11 是否使用移动语义来进行复制到分配优化?

c++ - -Wshadow=global 将枚举类条目视为全局阴影。为什么?

c++ - 关于编译器输出的异或浮点值和一般转换问题

C/GCC 警告 - 一次编写并到处测试?

linux - 在旧版本的 gcc 上使用 `-Wno-implicit-fallthrough`

c++ - 使用 SSE 的 OpenCV 灰度图像的平方根

c++ - 使用 LuaPlus 时的编译错误

c++ - 识别ffmpeg的rtsp断开连接

c++ - 如何说某物是否在其他东西中 C++

c - 如何指示 gcc 像 g++ 那样警告我有关无效函数指针转换的信息?