Structures Introduction

We have seen earlier how ordinary variables can hold one piece of information and how arrays can hold a number of pieces of information of the same data type. These two data types can handle a great variety of situations. But quite often we deal with entities that are collection of dissimilar data types.
For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int). If data about say 3 such books is to be stored, then we can follow two approaches:

  1. Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages.
  2. Use a structure variable.

Example (program that uses arrays)

#include <stdio.h>
int main() {
	char name[3];
	float price[3];
	int pages[3], i;
	printf("\nEnter names, prices and no. of pages of 3 books\n");
	for (i = 0; i <= 2; i++)
		scanf("%c %f %d", &name[i], &price[i], &pages[i]);

	printf("\nAnd this is what you entered\n");

	for (i = 0; i <= 2; i++)
		printf("%c %f %d\n", name[i], price[i], pages[i]);

	return 0;

This approach no doubt allows you to store names, prices and number of pages. But as you must have realized, it is an unwieldy approach that obscures the fact that you are dealing with a group of characteristics related to a single entity—the book.
The program becomes more difficult to handle as the number of items relating to the book go on increasing. For example, we would be required to use a number of arrays, if we also decide to store name of the publisher, date of purchase of book, etc. To solve this problem, C provides a special data type—the structure.
A structure contains a number of data types grouped together. These data types may or may not be of the same type.


#include <stdio.h>
int main() {
	struct book {
		char name;
		float price;
		int pages;
	struct book b1, b2, b3;
	printf("\nEnter names, prices & no. of pages of 3 books\n");
	scanf("%c %f %d", &, &b1.price, &b1.pages);
	scanf("%c %f %d", &, &b2.price, &b2.pages);
	scanf("%c %f %d", &, &b3.price, &b3.pages);

	printf("\nAnd this is what you entered");

	printf("\n%c %f %d",, b1.price, b1.pages);
	printf("\n%c %f %d",, b2.price, b2.pages);
	printf("\n%c %f %d",, b3.price, b3.pages);

	return 0;

See the diference in above codes, and it’s been very easy to figure out why we use structures.
So a structure type is a type defined within the program that specifies the format of a record, including the names and types of its members, and the order in which they are stored. Once you have defined a structure type, you can use it like any other type in declaring objects, pointers to those objects, and arrays of such structure elements.


You may also like...