8.1. Basic Data Structures¶
A structure, like an array, allows us to aggregate multiple pieces of data into a single named variable.
With structures, however, each member data element may have a distinct data type.
The
struct
keyword is used to define the data structure.struct employee { char *name; /* only alloc the pointer here. */ int ssn; int salary; enum job_grade position; /* any known data type may be used */ int hire_date; };
The
struct
construct only defines the structure. It is still necessary to declare a variable in order to use the structure.struct employee intern;
If we use
typedef
to define a new variable type, then we do not need to use the keywordstruct
when we make a reference to the structure in our program.typedef struct employee EMPLOYEE; -or- typedef struct employee { char *name; int ssn; .... } EMPLOYEE; EMPLOYEE intern;
Use a dot (
.
) to access member data for local variables. Use (->
) to access member data when the variable is a pointer.EMPLOYEE boss, *temp; int input_data; char input_string[50]; temp = &boss; temp->ssn = input_data; boss.name = (char *)calloc( strlen(input_string)+1, sizeof(char) ); strcpy( temp->name, input_string );
Homework 12 - Numerical Proof of Euler’s Formula provides an opportunity to build a program using a simple data structure.
8.2. Allocating memory for structures¶
It is common to dynamically allocate the memory for a structure, especially if we do not know in advance how much data will be stored.
struct employee *temp_employee;
if((temp_employee=(struct employee *)malloc(sizeof(struct employee))) == NULL) {
fprintf( stderr, "Memory allocation error\n" );
exit(1);
}