I need some help in C syntax, more about C casting syntax.
All information I found in web is about simple casts like (int) or (char) etc…
I always get stuck in casting void* to a array or multi-dimentisional array or pointers of such things, but I never know how to do that! All that I do in these cases was trying things like (char []) or (char *[]) or (*char []) without any idea what I’m doing, until I get no errors about type casting.
Anybody have a thumb of rule to follow or some tips or tricks to do that?
For example I have a arry of void pointers and I pass it to a function, how to turn it into array again?
main () {
int data1, data2;
char data3, data4;
void *function_data[] = {data1, data2, data3, data4};
some_function (function_data);
return;
}
some_function (void *data) {
void *function_d[4];
function_d = (void *[]) data; //It not work, how to cast data?
}
EDIT: I wrote wrong, I thinked that it wasn’t important, so, I changed the variables data* of my code for better undestand.
The basic idea is to use the type definition of the intended type without the variable name and placed in parentheses as a cast to that type. For example:
and
Of course always assuming the type cast is possible and makes sense. Be aware: C doesn’t prevent most nonsensical casts, so you’ll have to take care yourself.
In your case,
function_datais defined to be an array of pointers to void. Therefore, each data needs to be of typevoid **, as Keith already indicated.By calling
some_functionwithfunction_dataas parameter, you’re passing a pointer tofunction_data[0]into the function.In order for your function to use it again as an array of 4 pointers to void, you would need to use a cast like you did, (void*[]). However, the array
function_dis an array reserving also the space for four pointers, and you cannot change the function_d pointer (it is of typevoid * * const!). To do what you seem to want, you’ll need a non-const pointer, likeYou may then still use it in the same way like
function_data, using subscription like an array.function_d[2]will give you the value equal to*data3.