C Programming

Practise Exercise 11: Pointers & Structures

1. Declare a pointer to a structure of type date called dates.


	struct date *dates;

2. If the above structure of type date comprises three integer fields, day, month, year, assign the value 10 to the field day using the dates pointer.


	dates->day = 10;

3. A structure of type machine contains two fields, an integer called name, and a char pointer called memory. Show what the definition of the structure looks like.

	|-----------| <---------
	|           | name       |
	|-----------|            | machine
	|           | memory     |
	|-----------| <---------

4. A pointer called mpu641 of type machine is declared. What is the command to assign the value NULL to the field memory.


	mpu641->memory = (char *) NULL;

5. Assign the address of the character array CPUtype to the field memory using the pointer mpu641.


	mpu641->memory = CPUtype;

6. Assign the value 10 to the field name using the pointer mpu641.


	mpu641->name = 10;

7. A structure pointer times of type time (which has three fields, all pointers to integers, day, month and year respectively) is declared. Using the pointer times, update the field day to 10.


	*(times->day) = 10;

8. An array of pointers (10 elements) of type time (as detailed above in 7.), called sample is declared. Update the field month of the third array element to 12.


	*(sample[2]->month) = 12;



#include <stdio.h>

struct machine {
   int name;
   char *memory;
};

struct machine p1, *mpu641;

main()
{
   p1.name = 3;
   p1.memory = "hello";
   mpu641 = &p1;
   printf("name = %d\n", mpu641->name );
   printf("memory = %s\n", mpu641->memory );

   mpu641->name = 10;
   mpu641->memory = (char *) NULL;
   printf("name = %d\n", mpu641->name );
   printf("memory = %s\n", mpu641->memory );
}



#include <stdio.h>

struct time {
   int *day;
   int *month;
   int *year;
};

struct time t1, *times;

main()
{
   int d=5, m=12, y=1995;

   t1.day = &d;
   t1.month = &m;
   t1.year = &y;

   printf("day:month:year = %d:%d:%d\n", *t1.day, *t1.month, *t1.year );

   times = &t1;

   *(times->day) = 10;
   printf("day:month:year = %d:%d:%d\n", *t1.day, *t1.month, *t1.year );
}

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