1

Suppose I have a function signature:

bool func(const char** arrayOfStrings);

And I have a auxiliary function with signature:

char** auxFunc(not relevant);

For some reason I can manage to do the following:

func(auxFunc(not relevant));

I got compiler warnings/errors:

error: initializing 'const char *' with an expression of type 'char *' discards qualifiers in nested pointer types

Why this is not working as I expect it to, and what can I do about it?

triple fault
  • 13,410
  • 8
  • 32
  • 45

2 Answers2

2

You are asking the compiler to perform an implicit conversion from char ** to const char **, which dangerously violates the rules of const-correctness. This is why you get an error from the compiler.

Read the FAQ entry here to better understand the issue (there are numerous answers about that issue here on SO as well).

After that you should decide what's the best solution in your case: either redesign the code to eliminate the problem or suppress the error with an explicit cast. Nobody can do it for you without understanding your design/code in much greater detail (which you did not provide).

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 1
    Maybe better to link to the [C FAQ entry](http://c-faq.com/ansi/constmismatch.html) for a C question. – detly Dec 04 '13 at 02:56
-2

Unfortunately, C does not make an implicit cast from char ** to char const ** although this would be safe. You will have to cast it explicitly func((char const **)(auxFunc())).

ensc
  • 6,704
  • 14
  • 22
  • 2
    Safe? Absolutely not. `char **` is not implicitly convertible to `char const **` neither in C nor in C++. The conversion is unsafe, which is well explained in the FAQ: http://www.parashift.com/c++-faq/constptrptr-conversion.html – AnT stands with Russia Dec 04 '13 at 02:14