Structures ---------- Structure refers to how individual elements of a group are arranged or organized. For example, a corporation's structure refers to the organization of the people and departments in the company and a government's structure refers to its form or arrangement. In programming, a structure refers to the way individual data items are arranged to form a cohesive and related unit. You might also see a structure referred to as a record. The form of a structure consists of the symbolic names, data types and arrangement of individual data items in the structure. The content of a structure refers to the actual data stored in the symbolic names. An example usage of a structure in C is for a mailing list. A mailing list might have a name, address, city, state and a zip code. A structures in C could be defined like this for the mailling list: struct { char name[20]; char address[30]; char city[25]; char state[2]; int zip; } mail_addr; The structure name above is "mail_addr" and it contains all those fields inside of it. To refer to each field, simply use a . extension like this: mail_addr.name mail_addr.zip For example, if you wanted to print out the name and zip code you could use the statement: printf("The name is %s and zip is %d.\n", mail_addr.name, mail_addr.zip); To initialize elements, just make regular assignments liek this: mail_addr.zip = 77840; sprintf(mail_addr.name,"%s","Joe Texas"); sprintf(mail_addr.address,"%s","321 Oakland Dr."); Next, if you want to declare a bunch of the same structure, you can set up a structure and make it a data type like this: struct mail { char name[30]; char address[30]; int zip; }; Then to make variables of this data type, you simply type: struct mail name1; struct mail mail_addr; struct mail bunch[10]; These declarations refer to the data type "struct mail". To quickly initialize these, a similar technique may be used from before for arrays, like this: struct mail name1 = {"Greg Miller", "45 Regent Dr.", 53890}; Notice the fields how they match with the order of the structure listed above. Look at the last example above "struct mail bunch[10]". This is 10 structures. You may assign each in a loop if you would like or all at once. A loop example might be: for(i=0;i<10;i++) { scanf("%s", bunch[i].name); scanf("%s", bunch[i].address); scanf("%d", &bunch[i].zip); } If you want to pass structure into functions, simply pass the name of the structure and declare it a struct like this: void print_struct(struct mail a) { printf("name: %s\naddr: %s\nzip : %d\n", a.name, a.address, a.zip); } main() { struct mail { char name[20]; char address[20]; int zip; }; struct mail maillabel = {"Jill Fields","345 Tower Dr.",65432}; print_struct(maillabel); } You can return structures, but they must be a pointer type. We will skip this part of the section in Chapter 10 (10.3).