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

不羁岁月 提交于 2019-12-11 13:44:44

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18090893/passing-to-void-instead-void-makes-the-compiler-complain-about-types-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!