Sasquash
Sasquash

Reputation: 13

Passing to void** instead void* makes the compiler complain about types, why?

I don't understand why the compiler warn me about passing an incompatible pointer type in this code: (in this context what are the difference between void * and void **) (I don't know if this make some difference but I am using gnu99 C version)

void someFunc(void ** foo) {
    printf("%s\n", *foo);
}

int main() {

    char * text = "some text";
    someFunc(&text);

    return 0;
}

and in this not

void someFunc(void * foo) { 
    printf("%s\n", foo);
}

int main() {

    char * text = "some text";
    someFunc(text);

    return 0;
}

Thanks in advance

Upvotes: 1

Views: 182

Answers (2)

JackCColeman
JackCColeman

Reputation: 3807

To fix your code in the second example, you can do one of the following:

// Solution A, preferred:
void someFunc(char * foo) { 
    printf("%s\n", foo);
}

int main() {

    char * text = "some text";
    someFunc(text);

    return 0;
}

In A you are telling the compiler that the parameter being passed is a pointer to a char. I haven't tried solution B, should work but why use voids if they are NOT absolutely necessary.

// Solution B, should work but a purist might object:
void someFunc(void * foo) { 
    printf("%s\n", foo);
}

int main() {

    char * text = "some text";
    someFunc( (void *) text);

    return 0;
}

In this question there is no obvious reason to use a double ptr, so Solution A for your second example is probably the way to go.

Upvotes: 1

user529758
user529758

Reputation:

void * is a type that is implicitly convertible to and from any object pointer type. void ** isn't - so while you can assign a char * to a void *, you can not do the same with char ** and void **.

The reason is that they are incompatible types: char ** points to a char *, void ** points to a void *, so their base types don't match.

Upvotes: 6

Related Questions