Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Cast to void** needed?

Tags:

c

I have the compiler complaining (warning) about the folowing.

Am I missing something? Because I thought this didn't need a cast

char* CurrentCh  = some ptr value;
int size;

size = func(&CurrentCh);

with func defined like this

int func(void** ptr);

Compiler warning:

passing argument 1 of 'func' from incompatible pointer type

Thx

like image 635
matkas Avatar asked Dec 10 '22 17:12

matkas


2 Answers

In C you can pass any pointer type to a function that expects a void*. What it says is "I need a pointer to something, it doesn't matter what it points to". Whereas void** says "I need a pointer to a void*, not a pointer to another pointer type".

like image 118
Ferruccio Avatar answered Dec 23 '22 01:12

Ferruccio


In C, void * is the generic pointer type. But void ** is not a generic pointer-to-pointer type! If you want to be able to pass a pointer to a pointer in a generic way, you should use void * anyway:

#include <stdio.h>

void func(void *ptr)
{
    char **actual = ptr;
    const char *data = *actual;
    printf("%s\n", data);
}

int main(void)
{
    char *test = "Hello, world";
    func(&test);
    return 0;
}
like image 36
Alok Singhal Avatar answered Dec 23 '22 01:12

Alok Singhal