構造体の使用例について、実際に書いてみます。
#include <stdio.h>
int main(void)
{
//構造体のテンプレート宣言
struct data{
int no;
char name[10];
int age;
};
//初期化(「1」や「test」というひとつひとつの要素はメンバ)
struct data list1 = {1, "test !!!", 39};
//メンバが多い場合は折り返して書く
struct data list1 = {
1,
"test !!!",
39
};
//構造体メンバへのアクセス
printf("%d %s %d\n", list1.no, list1.name, list1.age);
//構造体変数へ値を代入する
list1.no = 3;
strcpy(list1.name, "cotytext!");
list1.age = 40;
return 0;
}
構造体に対するポインタもあります。この場合は、構造体をポインタで指し示すことになります。
#include <stdio.h>
int main(void)
{
//構造体のテンプレート宣言
struct data{
int no;
char name[10];
int age;
} list1;
//構造体のポインタを宣言
struct data *sp;
//ポインタへのアドレスの代入方法
//struct data list1;
sp = &list1;
//ポインタを使った構造体の参照方法(phpのクラスのメンバ変数へのアクセスに似ている)
printf("%d %c %d\n", sp->no, sp->name, sp->age);
return 0;
}
構造体配列について