/*example on structures */ #include #include int main (void) { /* define a structure template called mydetails */ /* mydetails is the tagname */ /* alternative methods are described at the bottom of this file */ struct mydetails { char my_name[30], address1[30], address2[30], address3[30]; int my_age; }; /* the variable MD is of the form defined by mydetails */ struct mydetails MD; /* now assign some values to the fields */ strcpy(MD.my_name,"Christian Hicks"); strcpy(MD.address1,"Stephenson Building"); strcpy(MD.address2,"Claremont Road"); strcpy(MD.address3,"Newcastle upon Tyne"); MD.my_age = 42; /*next look at how to pass structures to functions by value or by reference */ /*this procedure passes the structure by value */ void printname(struct mydetails M) { printf("My name is = %s\n",M.my_name); printf("M.my_age = %i\n",M.my_age); printf("Address line 1 = %s\n",M.address1); printf("Address line 2 = %s\n",M.address2); printf("Address line 3 = %s\n",M.address3); } /*this procedure passes the structure by reference i.e. just the pointer. this is faster because only the pointer is copied */ void printptrname(struct mydetails *p) { printf("pointer address is %p\n",p); printf("Address line 1 = %s\n",p->address1); printf("Address line 2 = %s\n",p->address2); printf("Address line 3 = %s\n",(*p).address3); printf("my age is %i\n",p->my_age); /*note the way that the field within the pointer is dereferenced */ /* it can be done either by (*p). or p-> */ } printname(MD); printptrname(&MD); printf("MD.my_age = %i\n",MD.my_age); /* the variable names is an array of mydetails */ struct mydetails names[1000]; /* the variable ptr is a pointer to a variable of type mydetails */ struct mydetails *ptr; } /* there are some alternative ways of defining structures the first does not use a tag name: struct { char my_name[30], address1[30], address2[30], address3[30]; int my_age; } variablename; The second uses a tag name and declares the variables: struct myname { char my_name[30], address1[30], address2[30], address3[30]; int my_age; } variablename, vn2; The third method is to define the type using typedef: typedef struct { char my_name[30], address1[30], address2[30], address3[30]; int my_age; } myname; we could then declare variables to be of the user defined type myname: myname v1,v2,v3; */