如何正确地将 char ** x 转换为 const char **
How to properly cast char ** x to const char **
我有以下变量。
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 char
或 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.
}
因此,将 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.
}
我有以下变量。
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 char
或 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.
}
因此,将 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.
}