Path: utzoo!attcan!uunet!viusys!uxui!unislc!ttobler From: ttobler@unislc.uucp (Trent Tobler) Newsgroups: comp.lang.c Subject: Re: Passing pointers to structures Message-ID: <1991Jan23.003921.28629@unislc.uucp> Date: 23 Jan 91 00:39:21 GMT References: <1991Jan19.055923.19423@unicorn.cc.wwu.edu> Distribution: comp Organization: Unisys, SLC Utah Lines: 76 From article <1991Jan19.055923.19423@unicorn.cc.wwu.edu>, by n8743196@unicorn.cc.wwu.edu (Jeff Wandling): > > Example: > > struct node { > int key; > }; > > > foo(h_ptr) > struct node *h_ptr; /* ?? */ > { > h_ptr->key=10; /* anything */ > } > > > main() > { > struct node *head; > > foo(head); OR foo(&head); /* ?? K&R 1, p91 says use '&head' > but this isn't the same. Or is > it? */ > } > > > How do I pass the pointer? And in the function "foo", how do I > access it? I want "head" to be passed by 'reference', but I don't know > I have K&R 1 in front of me and I checked the FAQ. If you can cite a > ::::::::::::::::::::::: If your purpose was to change the variable head (defined in main) to point to some structure that is created/looked-up in foo: You must declare foo() with ... foo(h_ptr) struct node **h_ptr; /* h_ptr is the address of a pointer to node */ and access h_ptr with ... (*h_ptr) = get_head(); /* assign the pointer to some node */ (*h_ptr)->key = key_value; /* assign a key to the node */ and call foo with ... struct node *head; /* this will contain the node pointer */ foo( &head); /* assign head to the node */ ::::::::::::::::::::::: If your purpose was different, that of simply affecting the elements **IN** the struct node variable, then this is the format: You must declare foo() with ... foo(h_ptr) struct node *h_ptr; /* h_ptr is a pointer to a node */ and access h_ptr with ... h_ptr->key = key_value; /* assign a value to the key element */ and call foo with ... struct node head; /* declare some space to store key */ foo( &head); /* change a field in head */ > -- > jeff wandling | western washington university | inet: jeff@arthur.cs.wwu.edu > cs ugrad | bellingham, wa 98225 USA | n8743196@unicorn.cc.wwu.edu -- Trent Tobler - ttobler@csulx.weber.edu