types - C++: char** to const char** conversion -


this question has answer here:

in c++, why not possible pass char** argument function accepts const char** , when conversion char* const char* possible, shown below

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

the compiler output

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

you need protect contents on both levels of dereference of pointer. const char** modify contents on 1st dereference.

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

and not intended. should this:

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

the compiler not allow implicit conversion such "partially" protected pointer types. allowing such conversion have nasty consequences discussed in c++faq pointed out in comment @zmb. answer cites how violate constness of object if allowed, using char examples.

one can implicitly convert "fully" protected pointer shown in 2nd code example below code compiles.

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

actually there bunch of questions , answers on matter lying around. e.g:

  1. invalid conversion ‘char**’ ‘const char**’
  2. why getting error converting ‘float**’ ‘const float**’?

edit: got 1st example wrong bit. thank pointing out!


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -