c - C99 pointer to compound literal array of pointers -


note: actively fiddling on over ideone.

i have (self-referential) structure:

typedef struct t_function t_function; struct t_function {     t_function * (* inhibits)[]; // pointer array of pointers structure }; 

and use compound literals target of inhibits pointer. along lines of

t_function a, b, c; a.inhibits = & (<type>) {&b, &c}; 

this done follows looking understand type specification can use compound literals.

t_function a, b, c; t_function * ai[] = {&b, &c}; a.inhibits = &ai; 

what appropriate type specification replace <type> above?

a.inhibits pointer subsequent memory locations forming pointer array. if want assign a.inhibits, need array of pointers somewhere location store in a.inhibits. why there no syntax &(...){&b, &c}: can't right regardless of using ... because there no actual array {&b, &c} in memory.

in second example, allocating array of t_function * pointers on stack. common programming error: a.inhibits point location on stack, , current stack frame left, contents of a.inhibits undefined. still worse, writing a.inhibits cause undefined behavior.

you'll want use data structure of kind, answer question, simplest solution allocate array on heap:

#include <stdlib.h>  typedef struct t_function t_function; struct t_function {     t_function **inhibits;  /* no [] */ }; 

t_function a, b, c; t_function **ai = calloc(2, sizeof(t_function *)); ai[0] = &b; ai[1] = &c; a.inhibits = ai; 

just make sure free memory once don't need more.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -