首页 文章

C:char **到const char **转换[重复]

提问于
浏览
24

这个问题在这里已有答案:

在C中,当从 char*const char* 的转换成为可能时,为什么不能将 char** 作为参数传递给接受 const char** 的函数,如下所示

void f1(const char** a)
{

}

void f2(const char* b)
{

}

int main(int argc, char const *argv[])
{
   char* c;

   f1(&c); // doesn't work
   f2(c); //works

   return 0;
}

编译器输出是

test.cpp: In function 'int main(int, const char**)':
test.cpp:15:10: error: invalid conversion from 'char**' to 'const char**' [-fpermissive]
test.cpp:1:6: error:   initializing argument 1 of 'void f1(const char**)' [-fpermissive]

1 回答

  • 23

    您需要在指针的两个取消引用级别上保护内容 . 使用 const char** ,您实际上可以修改第一个引用的内容 .

    char *tmp = "foo"; //Deprecated but it's ok for the example
    void f1(const char** a)
    {
      a[0] = tmp;     //this is legal
      a[0][1] = 'x';  //this is not
    }
    

    这很可能不是故意的 . 它应该如下所示:

    char *tmp = "foo"; //Deprecated but it's ok for the example
    void f1(char const* const* a)
    {
      a[0] = tmp;    // this is not legal any more
      a[0][1] = 'x'; // this still upsets compiler
    }
    

    编译器不允许隐式转换为此类"partially"受保护的指针类型 . 允许这样的转换可能会产生令人讨厌的后果,如@zmb在评论中所述 . 这个answer还引用了如果允许的话,你如何使用 char 例子来违反对象的常量 .

    然而,可以隐式地转换为“完全”受保护的指针,如第二个代码示例所示,因此在代码编译之下 .

    void f1(char const* const* a){}
    void f2(const char* b){}
    int main(int argc, char const *argv[])
    {
       char* c;
       f1(&c); // works now too!
       f2(c);  // works
       return 0;
    }
    

    实际上这个问题上有很多问题和答案 . 例如:

    编辑:我有点错误的第一个例子 . 感谢指出来!

相关问题