C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

Click here to view code image


item1 = (struct invStruct *)malloc(sizeof(invStruct));
item2 = (struct invStruct *)malloc(sizeof(invStruct));
item3 = (struct invStruct *)malloc(sizeof(invStruct));

Putting Data in Structure Variables


A new operator, the dot operator, lets you put data in a structure variable’s individual members.
Here is the format of the dot operator:


Click here to view code image


structureVariableName.memberName

To the left of the dot is always the name of a structure variable, such as item1 or employee[16].
To the right of the dot operator is always the name of a member from that structure, such as
quantity, cost, or name. The dot operator puts data only in named structure variables. If you
want to put data in a heap structure pointed to by a structure pointer variable, you must use the
structure pointer operator, ->.


The following program defines an array of three structure variables using a bookInfo structure tag
shown that is defined in the bookInfo.h header file presented first. The user is asked to fill the
structure variables, and then the program prints them. In the next couple chapters, you’ll see how to
output the structure variables to a disk file for long-term storage.


The first file is the header file containing the structure definition:


Click here to view code image


// Example program #A from Chapter 27 of Absolute Beginner's Guide
// to C, 3rd Edition
// File bookinfo.h
// This header file defines a structure for information about a book
struct bookInfo {
char title[40];
char author[25];
float price;
int pages;
};

And now the .c program file:


Click here to view code image


// Example program #1 from Chapter 27 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter27ex1.c
/* The program gets the bookInfo structure by including bookInfo.h
and asks the user to fill in three structures and then prints them.
*/
//First include the file with the structure definition
#include "bookinfo.h"
#include <stdio.h>
Free download pdf