menu prev next

POINTERS

Lets construct the actual list as shown below, as an example.

list of records


	program PointerRecordExample( output );

	type  rptr = ^recdata;
		recdata = record
			number : integer;
			code   : string;
			nextrecord : rptr
		end;

	var  startrecord : rptr;

	begin
		new( startrecord );
		if startrecord = nil then
		begin
			writeln('1: unable to allocate storage space');
			exit
		end;
		startrecord^.number := 10;
		startrecord^.code := 'This is the first record';
		new( startrecord^.nextrecord );
		if startrecord^.nextrecord = nil then
		begin
			writeln('2: unable to allocate storage space');
			exit
		end;
		startrecord^.nextrecord^.number := 20;
		startrecord^.nextrecord^.code := 'This is the second record';
		new( startrecord^.nextrecord^.nextrecord );
		if startrecord^.nextrecord^.nextrecord = nil then
		begin
			writeln('3: unable to allocate storage space');
			exit
		end;
		startrecord^.nextrecord^.nextrecord^.number := 30;
		startrecord^.nextrecord^.nextrecord^.code := 'This is the third record';
		startrecord^.nextrecord^.nextrecord^.nextrecord := nil;
		writeln( startrecord^.number );
		writeln( startrecord^.code );
		writeln( startrecord^.nextrecord^.number );
		writeln( startrecord^.nextrecord^.code );
		writeln( startrecord^.nextrecord^.nextrecord^.number );
		writeln( startrecord^.nextrecord^.nextrecord^.code );
		dispose( startrecord^.nextrecord^.nextrecord );
		dispose( startrecord^.nextrecord );
		dispose( startrecord )
	end.


The lines of code

		new( startrecord );
		if startrecord = nil then
		begin
			writeln('1: unable to allocate storage space');
			exit
		end;
		startrecord^.number := 10;
		startrecord^.code := 'This is the first record';
create the beginning of the list, which pictorially looks like,

startrecord


The lines of code

		new( startrecord^.nextrecord );
		if startrecord^.nextrecord = nil then
		begin
			writeln('2: unable to allocate storage space');
			exit
		end;
		startrecord^.nextrecord^.number := 20;
		startrecord^.nextrecord^.code := 'This is the second record';
link in the next record, which now looks like,

startrecord


The lines of code

		new( startrecord^.nextrecord^.nextrecord );
		if startrecord^.nextrecord^.nextrecord = nil then
		begin
			writeln('3: unable to allocate storage space');
			exit
		end;
		startrecord^.nextrecord^.nextrecord^.number := 30;
		startrecord^.nextrecord^.nextrecord^.code := 'This is the third record';
		startrecord^.nextrecord^.nextrecord^.nextrecord := nil;
link in the third and final record, also setting the last nextrecord field to nil. Pictorially, the list now looks like,

thirdrecord added

The remaining lines of code print out the fields of each record.


Copyright B Brown/P Henry/CIT, 1988-1997. All rights reserved.
menu prev next