C Programming

STRUCTURES CONTAINING POINTERS
Naturally, a pointer can also be a member of a structure.


	struct  int_pointers {
		int  *ptr1;
		int  *ptr2;
	};

In the above, the structure int_pointers is defined as containing two integer pointers, ptr1 and ptr2. A variable of type struct int_pointers can be defined in the normal way, eg,


	struct  int_pointers  ptrs;

The variable ptrs can be used normally, eg, consider the following program,


	#include <stdio.h>
	main()   /* Illustrating structures containing pointers */
	{
		struct  int_pointers {  int  *ptr1, *ptr2;  };
		struct int_pointers  ptrs;
		int  i1 = 154, i2;

		ptrs.ptr1 =  &i1;
		ptrs.ptr2 =  &i2;
		*ptrs.ptr2 =  -97;
		printf("i1 = %d, *ptrs.ptr1 = %d\n", i1, *ptrs.ptr1);
		printf("i2 = %d, *ptrs.ptr2 = %d\n", i2, *ptrs.ptr2);
	}

The following diagram may help to illustrate the connection,

	|------------|
	|  i1        |<--------------
	|------------|               |
	|  i2        |<-------       |
	|------------|        |      |
	|            |        |      |
	|------------|        |      |
	|  ptr1      |---------------
	|------------|        |           ptrs
	|  ptr2      |--------     
	|------------|


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