C 言語 | 構造体の宣言 | 構造体のメンバー
構造体は、別の構造体や構造体へのポインターをメンバーとして保持できる。これにより複雑なデータモデルを作成できる。
構造体を含む構造体
struct Point { int x, y; };
struct Size { int width, height; };
struct Rectangle {
struct Point location;
struct Size size;
};
入れ子になったメンバーは、外側の構造体から順番にアクセスする。
rect.size.width
rect->size.width
コード 1
#include <stdio.h>
struct Point { int x, y; };
struct Size { int width, height; };
struct Rectangle { struct Point location; struct Size size; };
int main() {
struct Rectangle rect = { 100, 50, 400, 300 };
printf("Location (%d, %d): Size (%d, %d)\n",
rect.location.x, rect.location.y, rect.size.width, rect.size.height);
return 0;
}
自己参照構造体
構造体は自分自身のインスタンスを直接メンバーにできない。サイズを確定できないためである。
struct Node { struct Node node; }; /* 無効 */
同じ型へのポインターなら保持できる。
struct Node { struct Node *next; };
このパターンは連結リストや木構造に便利である。
コード 2
#include <stdio.h>
struct Chain {
char *text;
struct Chain *next;
};
void ShowChain(struct Chain *chain) {
if (chain == NULL) return;
printf("%s\n", chain->text);
ShowChain(chain->next);
}
int main() {
struct Chain first = { "First Chain", NULL };
struct Chain second = { "Second Chain", NULL };
first.next = &second;
ShowChain(&first);
return 0;
}