Basic Pascal Tutorial/Chapter 5/Pointers/ja

From Free Pascal wiki
(Redirected from Pointers/ja)
Jump to navigationJump to search

български (bg) English (en) français (fr) 日本語 (ja) 中文(中国大陆)‎ (zh_CN)

5F - ポインタ (著者: Tao Yue, 状態: 原文のまま変更なし)

ポインタ はメモリ・アドレスを持ったデータタイプである。 ポインタはそのメモリアドレスへの参照と考えることができる。一方、変数はそのメモリアドレスに直接アクセスする。もし、変数が誰かの電話番号なら、ポインタは電話帳に載っているページや行番号に相当する。そのメモリアドレスに保存されているデータにアクセスするためには、ポインタを参照する。

メモリ・ルーチン

ポインタ・データ型を宣言するためには、それが指し示すものを指定しなくてはならない。データ・タイプの前にはキャラット (^) をつける。 たとえば、整数でポインタを作成するなら、次のようなコードを用いる。

type
	PointerType = ^integer;

もちろん、その後で変数をPointerTypeと宣言することができる。

ポインタにアクセスする前に、アクセスするポインタのためにメモリのその部分を遮断する。 そのためには次のようにする。

New(PointerVariable);

ポインタのメモリ位置にあるデータにアクセスするためには、ポインタ名のあとにキャレット(^)を加える。 For example, if PointerVariable was declared as type PointerType (from above), you can assign the memory location a value by using:

PointerVariable^ := 5;

After you are done with the pointer, you must deallocate the memory space. Otherwise, each time the program is run, it will allocate more and more memory until your computer has no more. To deallocate the memory, you use the Dispose command:

Dispose(PointerVariable);

A pointer can be assigned to another pointer. However, note that since only the address, not the value, is being copied, once you modify the data located at one pointer, the other pointer, when dereferenced, also yields modified data. Also, if you free (or deallocate) a pointer, the copied pointer now points to meaningless data.

Trivial usage example: singly linked lists

What is a pointer good for? Why can't you just use an integer in the examples above instead of a pointer to an integer? Well, the above is clearly a contrived example. The real power of pointers is that, in conjunction with records, it makes dynamically-sized data structures possible. If you need to store many items of one data type in order, you can use an array. However, your array has a predefined size. If you don't have a large enough size, you may not be able to accommodate all the data. If you have a huge array, you take up a lot of memory when sometimes that memory is not being used.

A dynamic data structure, on the other hand, takes up only as much memory as is being used. What you do is to create a data type that points to a record. Then, the record has that pointer type as one of its fields. E. g. stacks and queues can all be implemented using this data structure:

type
	PointerType = ^RecordType;
	RecordType = record
		data : integer;
		next : PointerType;
	end;

Each element points to the next. The last record in the chain indicates that there is no next record by setting its next field to a value of nil.

previous contents next