c - C99 pointer to a struct which contains a pointer to a struct -


the k&r "the c programming language" 2nd edition says on page 131 given set of variables :

struct rect r, *rp = &r; 

where :

struct rect {     struct point pt1;     struct point pt2; }; 

and

struct point {     int x;     int y; } 

then these 4 expressions equivalent :

r.p1.x rp->pt1.x (r.pt1).x (rp->pt1).x 

earlier on same page see :

p->member_of_structure 

which described "refers particular member".

i changed hyphens underscores ensure not confused minus sign.

so great, can see have refer nested struct because struct rect contains within struct point.

well definition of rect such pt1 , pt2 both pointers struct point?

here hit troubles following code bits :

typedef struct some_node {     struct timespec *tv;     struct some_node *next; } some_node_t; 

clearly making linked list here , no problem.

what big problem :

struct timespec some_tv; clock_gettime( clock_realtime, &some_tv ) /* set head node */ struct some_node *node_head =                 ( struct some_node * ) malloc( sizeof( some_node_t ) ); node_head->tv = calloc ( (size_t) 1, sizeof ( struct timespec ) ); 

that works great , node_head fine. nested struct timespec node_head->tv fine.

what real problem trying figure out how set inner tv.sec value in some_tv.sec :

((struct timespec *)(*node_head.tv)).tv_sec = some_tv.tv_sec; 

i error :

line 22: error: left operand of "." must struct/union object 

so looking in k&r , see example in book not have pointer struct within struct rect.

i have resorted trial , error want maddening. create temporary variable of type "struct timespec temp" , set temp = &node_head.tv ... no ... won't work. worse think.

what missing here ?

the answer trivial, of course, use foo->bar->here syntax.

modify code drop cast on malloc , use correct syntax :

/* set node list */ struct some_node *node_head =                 calloc( (size_t) 1, sizeof( some_node_t ) );  node_head->tv = calloc ( (size_t) 1, sizeof ( struct timespec ) ); node_head->tv->tv_sec = some_tv.tv_sec; node_head->tv->tv_nsec = some_tv.tv_nsec; node_head->next = null; 

the debugger confirms :

(dbx) print *node_head *node_head = {     tv      = 0x1001453e0     next    = (nil) }  (dbx) print *node_head.tv *node_head->tv = {     tv_sec  = 1363127096     tv_nsec = 996499096 } 

works great. clearly, need coffee. :-)

isn't sufficient?

node_head->tv->tv_sec 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -