constness and pointers to pointers

后端 未结 4 469
时光取名叫无心
时光取名叫无心 2020-11-30 13:15

I\'m very much confused about the const keyword. I have a function accepting an array of strings as input parameter and a function accepting a variable number o

4条回答
  •  情书的邮戳
    2020-11-30 13:55

    You cannot pass char ** into const char ** because the compiler cannot guarantee const correctness.

    Suppose you had the following code (and it compiled):

    void foo(const char **ppc, const char* pc)
    {
      *ppc = pc; // Assign const char* to const char*
    }
    
    void bar()
    {
      const char c = 'x';
      char* pc;
    
      foo(&pc, &c); // Illegal; converting const char* to const char**. Will set p == &c
      *pc = 'X';    // Ooops! That changed c.
    }
    

    See here for the same example without the function calls.

提交回复
热议问题