I’ve come across some C code that I don’t quite understand. The following compiles and runs just fine. 1) Why can I cast a char* to a struct* and 2) is there any advantage to using this idiom instead of a void* ?
struct foo
{
int a;
int b;
char *nextPtr;
};
. . .
// This seems wrong
char *charPtr = NULL;
// Why not
//void *structPtr = NULL;
struct foo *fooPtr;
fooPtr = (struct foo*)charPtr;
// Edit removing the string portion as that’s not really the point of the question.
You can convert between pointer types because this is the flexibility the language gives you. However, you should be cautious and know what you are doing or problems are likely.
No. There is an advantage to using the property pointer type so that no conversion is needed. If that isn’t possible, it doesn’t really matter if you use void*, although it may be slightly more clear to developers reading your code.