struct いろいろ


さて、基本的な structure の使い方は分かったので、ちょっと込み入った例を見ていきましょう。

structure のsize

単純に、 sizeof(struct XXXX)などとすればいいだけです。

structure の配列

配列さえ分かっていれば、別に難しいことはありません。
    struct List lists[20]; 
とやれば、構造体用の領域が 20 個分でき、 listsという定数値が、その配列の先頭アドレスを指すことに なります。listsは、structure List へのpointer型なので、 lists+1は、 第1番目の要素(lists[1])をさすという具合いです。

structure の中に配列

structure は、int などのデータ以外に配列も含むことができます。
struct STR0 {
    int tag;
    int items[20];
    int color;
};
/* アクセスイメージ 
 * struct STR0 * str0;
 * str0->items[10] = 4;
 */
ならば、struct STR0 は、int tag と items というサイズ 20の配列と int colorを内部に持つ ことになります。多くの処理系では、int データ 22個分の領域(88byte)消費することになるでしょう。

structure の中に structure

structure の中に structure を含むこともできます。当然、外側の strucuture は、そこそこ大きくなります。
struct STR1out {
    int tag;
    struct STR1in { /* STR1in にあまり意味はない*/
        int val;
        int bgcolor;
    } body;
    int color;
};
/* アクセスイメージ
 * struct STR1out * str1;
 * int bgcolor = str1->body.val;
 */
この例の用に中に含まれる struct の定義を同時に行っても構いません。 この例だと、STR1in という名前は使いませんので、省略しても構いません。

ちなみに、structure の中に structure の配列を入れてもらっても構いません。

struct STR1out {
    int tag;
    struct STR1in { /* STR1in にあまり意味はない*/
        int val;
        int bgcolor;
    } body[1];       /* size は 1 でも 2でも定数ならOK */
    int color;
};
/* アクセスイメージ
 * struct STR1out * str1;
 * int bgcolor = str1->body->val;
 */

2001.11.19/ Tomio KAMADA: kamada@cs.kobe-u.ac.jp