C Programming

POINTERS AND STRUCTURES
Consider the following,


	struct date {
		int month, day, year;
	};

	struct date  todays_date, *date_pointer;

	date_pointer = &todays_date;

	(*date_pointer).day = 21;
	(*date_pointer).year = 1985;
	(*date_pointer).month = 07;

	++(*date_pointer).month;
	if((*date_pointer).month == 08 )
		......

Pointers to structures are so often used in C that a special operator exists. The structure pointer operator, the ->, permits expressions that would otherwise be written as,


	(*x).y

to be more clearly expressed as


	x->y

making the if statement from above program


	if( date_pointer->month == 08 )
		.....


	/* Program to illustrate structure pointers */
	#include <stdio.h>

	main()
	{
		struct date { int month, day, year; };
		struct date today, *date_ptr;

		date_ptr = &today;
		date_ptr->month = 9;
		date_ptr->day = 25;
		date_ptr->year = 1983;

		printf("Todays date is %d/%d/%d.\n", date_ptr->month, \
			date_ptr->day, date_ptr->year % 100);
	}

So far, all that has been done could've been done without the use of pointers. Shortly, the real value of pointers will become apparent.


©Copyright B Brown. 1984-1999. All rights reserved.