Explain Pointers and Structures with example

Explain Pointers and Structures with example

These are fairly straight forward and are easily defined. Consider the following:

   struct COORD {float x,y,z;} pt;
         struct COORD *pt_ptr;


pt_ptr = &pt; /* assigns pointer to pt */
the  operator lets us access a member of the structure pointed to by a pointer.i.e.:
   pt_ptr x = 1.0;
   pt_ptr y = pt_ptr y - 3.0;

Example: Linked Lists

  typedef struct {  int value;
                         ELEMENT *next;
                 } ELEMENT;


ELEMENT n1, n2;


n1.next = &n2;
  
Fig.   Linking Two Nodes NOTE: We can only declare next as a pointer to ELEMENT. We cannot have a element of the variable type as this would set up a recursive definition which is NOT ALLOWED. We are allowed to set a pointer reference since 4 bytes are set aside for any pointer.
The above code links a node n1 to n2 (Fig. 9.6) we will look at this matter further in the next Chapter.

Labels: