Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to pass an address of array of type char *[2] to function taking char ***

My XCode (default compiler should be clang?) shows me on this code a warning:

Incompatible pointer types passing 'char *(*)[2]' to parameter of type 'char ***' (when calling func)

void func (char ***arrayref, register size_t size) {
    /// ...
}

int main()
{
    char *array[2] = {"string", "value"};
    func(&array, 2);
}

while this code is no problem (=no warning):

void func (char **arrayref, register size_t size) {
    /// ...
}

int main()
{
    char *array[2] = {"string", "value"};
    func(array, 2);
}

While this removes the warning

func((char***)&array, 2);

I still don't know why the first emits a warning, while the latter doesn't.

Also, when the first is a problem, I'd also expect that the first emits a warning like:

Incompatible pointer types passing 'char *[2]' to parameter of type 'char **'

like image 776
bwoebi Avatar asked Sep 06 '13 16:09

bwoebi


1 Answers

char *array[2] = {"string", "value"};

is an array with 2 elements of char *.

Using array as an address results to a pointer to the first element, i. e. of type char **.

Using &array results to a pointer to the same place, but of type char *(*)[2] (not sure if the spelling is right).

This is not the same as a char *** - the representation in memory is completely different.

To be more verbose,

+++++++++++++++++++++++
+ array[0] + array[1] +
+++++++++++++++++++++++

this is the array.

char ** p1 = array; // is a pointer to the first element, which in turn is a pointer.
char *(*p2)[2] = &array; // is a pointer to the whole array. Same address, but different type, i. e. sizeof(*p1) != sizeof(*p2) and other differences.

char ***p3 = &p1; // Now, p1 is a different pointer variable which has an address itself which has type `char ***`.
like image 185
glglgl Avatar answered Sep 28 '22 02:09

glglgl