Structures (or structs) are a very convenient way of collecting disparate data types into a single data element. The following example shows how a struct is defined as a type, how a variable of that type is declared, and how to access data fields in the struct:
#include <stdio.h> #include <assert.h> struct dates_s { int month; int day; int year; }; void showdate(struct date_s *date) { assert(date != NULL); (void) printf("Date = %02i/%02i/%4i\n",date->month,date->day,date->year); } void main(void) { struct date_s date; date.month = 1; date.day = 27; date.year = 2004; showdate(&date); }
Note that, unlike for arrays, the name of a structure is not a pointer to the structure. This means you can pass the actual value (contents) of the structure to a function. However, it's generally more efficient to just pass a pointer, as in the example above, to avoid copying data unnecessarily.