Passing pointers to structures
Trent Tobler
ttobler at unislc.uucp
Wed Jan 23 11:39:21 AEST 1991
>From article <1991Jan19.055923.19423 at unicorn.cc.wwu.edu>, by n8743196 at 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 at arthur.cs.wwu.edu
> cs ugrad | bellingham, wa 98225 USA | n8743196 at unicorn.cc.wwu.edu
--
Trent Tobler - ttobler at csulx.weber.edu
More information about the Comp.lang.c
mailing list