c - Why we cannot dynamically allocate a pointer to a function? -
i tried dynamically allocate pointer function that
void (*f)(void*); f = (*f)malloc(sizeof(f) * 2);
and got error.
error: expected ';' before 'malloc'
after searched, discovered cannot dynamically allocate pointer function, can declare array. in first step, declare array of functions
void (f[2])(void*);
and saw got error, cannot declare array of functions, must declare array of pointers functions.
void (*f[2])(void*);
in search discovered too, pointer function doesn't point data, points code. if can explain me why cannot dynamically allocate pointer function , why cannot have array of function instead of array of pointers functions.
my code following:
#include <stdio.h> #include <stdlib.h> void printnr(void *nr) { printf("%i\n", nr); } void printchar(void *ch) { printf("%c\n", ch); } int main(void) { void (*f)(void*); f = (*f)malloc(sizeof(f) * 2); f = printnr; (f + 1) = printchar; (*f)(15); (*(f + 1))('t'); return (0); }
there's sorts of ill defined (if not undefined) behaviour in 2 functions you've defined. you're living dangerously (at best) code. define functions take int
, ok (changing function pointer type too).
however, guess that's tangential immediate problem — (*f)
before malloc()
spurious. if want cast there, you'd need (void (**)(void *))
specify pointer pointer function returning void
, taking void *
argument.
here's fixed code type of function changed suggested:
#include <stdio.h> #include <stdlib.h> static void printnr(int nr) { printf("%i\n", nr); } static void printch(int ch) { printf("%c\n", ch); } int main(void) { void (**f)(int); f = (void(**)(int))malloc(sizeof(*f) * 2); f[0] = printnr; f[1] = printch; (*f)(15); (*(f + 1))('t'); free(f); return(0); }
note assignments (to f[0]
, f[1]
) fixed too. if must use non-array notation, *(f + 0)
, *(f + 1)
self-consistent , *f
, *(f+1)
work.
it easier use typedef pointer function type.
#include <stdio.h> #include <stdlib.h> typedef void (*functionptr)(int); static void printnr(int nr) { printf("%i\n", nr); } static void printch(int ch) { printf("%c\n", ch); } int main(void) { functionptr *f = (functionptr *)malloc(sizeof(*f) * 2); f[0] = printnr; f[1] = printch; (*f)(15); (*(f + 1))('t'); free(f); return(0); }
note can't use typedef while defining functions. it's curious quirk of c can't that, if define function type instead of function pointer type. example, given typedef void function(int);
, can't define static function printnr { … }
or similar , have mean same functions defined. trying static function *returnsptr(int n) { … }
compiles (if body appropriate) returns function pointer (function *
or functionptr
).
the cast malloc()
isn't needed if you're using c compiler. if you're using c++ compiler, needed. code (both programs) frees allocated memory. neither program checks allocation — slap wrist.
Comments
Post a Comment