简体   繁体   English

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

[英]How to properly cast char ** x to const char **

I have the following variable.我有以下变量。

char **arr

Then I want to perform some modification on array which means it can't be declared as a constant.然后我想对数组进行一些修改,这意味着它不能被声明为常量。

Now I have a function that accepts the argument of type const char ** arr .现在我有一个 function 接受const char ** arr类型的参数。 But I have no control over the signature of this function.但是我无法控制这个 function 的签名。

Now when I cast arr to const char ** arr g++ generates a warning which is [-Werror=cast-qual] .现在,当我将arr转换为const char ** arr g++ 时会生成一个警告,即[-Werror=cast-qual]

For more clarification consider following MCVE:有关更多说明,请考虑关注 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;


So my question is why this generates a warning?所以我的问题是为什么这会产生警告? Is there any risk in doing this?这样做有什么风险吗?

And how to achieve a behavior I want to achieve?以及如何实现我想要实现的行为?

Allowing a cast from char** to const char** provides a loophole to modify a const char or a const char* .允许从char**转换为const char**提供了修改const charconst char*的漏洞。

Sample code:示例代码:

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

Hence, casting a char** to const char** is not a safe cast.因此,将char**转换为const char**不是安全的转换。


You can use您可以使用

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

for your code to compile without the cast-qual warning.让您的代码在没有cast-qual警告的情况下编译。

If you need to pass more than just the first argument, you'll need to construct an array of const char* and use it.如果您需要传递的不仅仅是第一个参数,则需要构造一个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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM