c++ - 从 char** 到 const char** 的隐式转换

标签 c++ c string gcc casting

为什么我的编译器 (GCC) 没有从 char** 隐式转换为 const char**

以下代码:

#include <iostream>

void print(const char** thing) {
    std::cout << thing[0] << std::endl;
}

int main(int argc, char** argv) {
    print(argv);
}

给出以下错误:

oi.cpp: In function ‘int main(int, char**)’:
oi.cpp:8:12: error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive]
oi.cpp:3:6: error:   initializing argument 1 of ‘void print(const char**)’ [-fpermissive]

最佳答案

这样的转换将允许您将 const char* 放入您的 char* 数组中,这是不安全的。在 print 你可以这样做:

thing[0] = "abc";

现在 argv[0] 将指向一个无法修改的字符串字面量,而 main 期望它是非常量(char*)。所以为了类型安全,这种转换是不允许的。

关于c++ - 从 char** 到 const char** 的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7016098/

相关文章:

调用需要 const char8 string[] 作为参数的 c 函数的正确方法

swift - 从时间戳创建字符串值时,发生崩溃 [Swift]

c++ - 代码守卫失败,模板来自字符串文字

c++ - QCustomPlot 添加 QCustomItemText

c++ - 将非常量左值引用绑定(bind)到右值

c - C语言如何打印 "\\0"

c++ - 具有不同模板参数作为输入的模板类的友元函数

c++ - 用户空间和内核空间进程中的一组信号处理程序

python - 当它对整个句子调用reverse,然后对每个单词调用reverse时,这个解决方案如何反转句子中的单词 O(N)?

Python 3.4 - 列表元素可以进行 str() 而不是 int() 转换