1

So I have a library function that takes in a const char ** as one of its parameters to represent an array of char *s.

void libraryFunc(const char ** parameter);

So what I'm doing currently is this (all in C btw):

char *string1 = "myString";
char *string2 = "myString2";
char *stringArray[2] = { string1, string2 };
libraryFunc(&stringArray[0]);

^That causes a compiler error saying "No matching call to libraryFunc". I've also tried the following:

libraryFunc(stringArray);
libraryFunc(&stringArray);

Can't seem to figure it out.

user1782677
  • 1,963
  • 5
  • 26
  • 48

2 Answers2

2

You can either cast it:

libraryFunc( (const char **) stringArray);

or, preferably, just change the declaration of your array:

char *string1 = "myString";
char *string2 = "myString2";
const char *stringArray[2] = { string1, string2 };
libraryFunc(stringArray);

You cannot implicitly convert a char ** to a const char ** because that only works at the first level of indirection (note in the second extract above you're implicitly converting char * to const char * which, since it's at the first level of indirection, is fine). This question from the comp.lang.c FAQ goes into a bit more detail as to why it works this way.

Crowman
  • 25,242
  • 5
  • 48
  • 56
  • So should it be libraryFunc((const char **)stringArray) or libraryFunc((const char **) & stringArray[0]) ? – user1782677 Oct 06 '14 at 00:58
  • It should be how I've written it in my answer. Your second alternative is not wrong, just unnecessary, non-idiomatic, and verbose. `stringArray` gets implicitly converted to a pointer to its first element automatically, in this context. And, by the way, `stringArray` is a reserved identifier in C, you should call your array something else. Same goes for `string1` and `string2`. – Crowman Oct 06 '14 at 01:01
  • Thanks. I'm not actually calling them "stringArray" and "string1" in my code. I just changed the names of my variables for the sake of this question. – user1782677 Oct 06 '14 at 01:17
0

This is because you are trying to pass

char* - a pointer

to

const char** - pointer to pointer to const char

The use of const is a contract and you cannot meet this contract by going through the indirection of two pointers. It is so because otherwise you would be able always to change this const char applying procedure like this (this is taken from C++ Standard, with my comments):

const char c = 'c';
char* pc;
const char** pcc = &pc;   // not allowed (thankfully!)
                ^^^ here the bundit is hidden under const: "I will not modify"
*pcc = &c;                // *pcc is "pointer to const" right? so this is allowed...
*pc = 'C';                // would allow to modify a const object, *pc is char right?

For more details you can follow my other answer on similar topic: https://stackoverflow.com/a/16390371/1141471

Code online:

http://coliru.stacked-crooked.com/a/74392c59cfc3ef70

Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118