A structure (keyword: 'struct') is a data type consisting of a sequence of members whose storage is allocated in an ordered sequence. The flexibility and variety of structures is unlimited. Structures can contain numerous data types, INCLUDING other structures. Let's get to know this useful programming feature.
Access to a structure's element is done using " . element_name ". Such as 'a_p.age' below. The structure 'a_p' has a numeric element named 'age'. |
/* pgm10 source */
#include <stdio.h>
#include <string.h>
// the structure declaration does NOT allocate any memory
struct a_person {
char firstname[40];
char midname[30];
char lastname[40];
char nickname[20];
int height; // in inches
int weight; // in pounds
int age;
int bros_sist; // how many siblings
float temp_now; // in degrees F
};
int main(void) {
struct a_person a_p; // here's where memory storage IS allocated, and said memory is named 'a_p'
float feet_tall;
strcpy(a_p.firstname, "Reginald");
strcpy(a_p.midname, "Caruthers");
strcpy(a_p.lastname, "Slimperenton");
strcpy(a_p.nickname, "Reg");
a_p.height = 68; // 'Reg' is under 6 feet tall
// (float) is called a 'cast', which seeks to
// convert one datatype into a different datatype
// without (float) below, 'feet_tall' would
// display as '5.00', loosing the fractional data
feet_tall = (float) a_p.height / 12;
a_p.weight = 174; // 'Reg' is somewhat slender
a_p.age = 26;
a_p.bros_sist = 0; // 'Reg' is an only child
a_p.temp_now = 98.7;
printf("\nMeet my friend %s\n\n", a_p.nickname);
printf("%s %s %s is %d years old\n", a_p.firstname, a_p.midname, a_p.lastname, a_p.age);
printf("%d inches tall, %d pounds weight\n\n", a_p.height, a_p.weight);
printf("(by the way, %d inches equals %.2f feet)\n\n", a_p.height, feet_tall);
printf("%s has %d brothers/sisters\n\n", a_p.nickname, a_p.bros_sist);
printf("The nurse says %s's temp right now is %.1f\n\n", a_p.nickname, a_p.temp_now);
return(0);
}