c - Using right pointer type, dont want to cast with void * -
question regarding using correct pointer type in below code. when try initialize struct member function without type casting void *, got “initialization incompatible pointer type” warnings
?
problem solved typecasting want use right pointer type instead of casting void*.
code snippet:
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef void (*set_id)(int id); typedef void (*set_name)(char *name); typedef struct prop { set_id *cb_setting_id; set_name *cb_setting_name; }prop; prop *setting_id(int id) { printf("id:%d\n", id); } prop *setting_name(char *in) { char *name; name = in; printf("name:%s\n", name); } //here type casted void *, if not wrong pointer initalization //error prop cb_prop = { .cb_setting_id=(void *)setting_id, .cb_setting_name=(void *)setting_name }; int main() { prop *cb_event; cb_event = &cb_prop; cb_event->cb_setting_id = (void*)setting_id(2); cb_event->cb_setting_name = (void*)setting_name("/dev/ttys1"); return 0; }
without type casting, warning are:
struct_callback.c:25:33: warning: initialization incompatible pointer type [-wincompatible-pointer-types] prop cb_prop = { .cb_setting_id=setting_id, ^ struct_callback.c:25:33: note: (near initialization ‘cb_prop.cb_setting_id’) struct_callback.c:32:26: warning: assignment incompatible pointer type [-wincompatible-pointer-types] cb_event->cb_setting_id = setting_id(2);
check definition of e.g. set_id
type alias, pointer function taking int
argument , not returning anything. compare setting_id
function, function takes int
arguments , returns pointer prop
. 2 types not compatible. it's made worse because setting_id
function declared return pointer prop
doesn't return anything.
and not that, members in structure pointers e.g. set_id
means cb_setting_id
pointer pointer function.
later on do
cb_event->cb_setting_id = (void*)setting_id(2);
this wrong because calls setting_id
function, , tries assign returned value cb_event->cb_setting_id
. setting_id
function doesn't return anything.
the solution first problem make sure both set_id
type , function setting_id
equal.
the solution second problem not declare members pointers (since are), or changing set_id
not pointer.
the solution third problem remove lines, since the first 2 solutions should solve initial initialization of cb_prop
structure.
Comments
Post a Comment