Lecture
Structures
Structure defines set of data, but individual parts do not have to be the same type.
Example 1.1
struct hurricane
{
char name[10];
int year,category;
};
Within a structure, variables and even arrays can be defined. Structures are also known as aggregate data types since multiple data values can be collected into a single data type. Individual values within a structure are called data members, and each member is given a name. In Example 1.1, the names of the data members are name, year, and category. To refer to a data member, the structure variable name followed by a period and a data member name is used.
Definition and Initialization
- Define structure. Keyword struct used to define name of structure (aka structure tag) and data members that are included in structure
- After structure defined, structure variables can be defined using declaration statements. Semicolon required after structure definition.
- Statements can appear before main function but are often stored in header file.
- Statements do not reserve memory, they only define structure.
Example 1.2
struct hurricane h1; //define structure
Variable named h1 has 3 data members.
Declaration statement allocates memory, but initial values have not been assigned and are therefore unknown. Data members of structure can be initialized in declaration statement or with program statements.
Example 1.3
struct hurricane h1={"Camille",1969,5}; //initialize structure with declaration statement
Example 1.4
//Initialize structure using program statements
h1.name="Camille";
h1.year=1969;
h1.category=5;
Input and Output
scanf or fscanf statements can be used to read values into data members of a structure
Example 2.1
/* *//* This program reads the information for a hurricane */
/* from a data file and then prints it. */
#include <stdio.h>
#define FILENAME "storms2.txt"
/* Define structure to represent a hurricane. */
struct hurricane
{
char name[10];
int year, category;
};
int main(void)
{
/* Declare variables. */
struct hurricane h1;
FILE *storms;
/* Read and print information from the file. */
storms = fopen(FILENAME,"r");
if (storms == NULL)
printf("Error opening data file. \n");
else
{
while (fscanf(storms,"%s %d %d",h1.name,&h1.year,&h1.category) == 3)
{
printf("Hurricane: %s \n",h1.name);
printf("Year: %d, Category: %d \n",h1.year,h1.category);
}
fclose(storms);
}
/* Exit program. */
return 0;
}
Comments
Post a Comment