struct 構造体タグ名
{
メンバの型 メンバ名
…
};
struct data
{
char name[20];
int age;
float weight;
float height;
};
|
|
typedef 既存の型 新しい型名;
typedef struct data
{
char name[20];
int age;
float weight;
float height;
} DATA;
struct 構造体タグ名 構造体名; struct data mydata; |
|
struct 構造体タグ名 構造体名 = { メンバ1, メンバ2,,, };
struct data mydata = { "Deguchi", 40, 85.0, 170.0 };
|
|
構造体名.メンバ名 構造体へのポインタ->メンバ名 struct data newdata; struct data *p, *q; mydata.age = 41; p = &mydata; p->weight = 86; strcpy( newdata.name, mydata.name); q = &newdata; q->height = p->height; |
|
|
|
/* 構造体のメンバを表示する関数1 */
#include <stdio.h>
#include <string.h>
typedef struct data
{
char name[20];
int age;
float weight;
float height;
} DATA, *Data;
/*
DATA は struct data 型
Data は struct data 型へのポインタ
*/
/* void prdata( struct data d ) と書いても良いが... */
void prdata( DATA d )
{
printf("名前 = %s\n", d.name );
printf("年齢 = %d\n", d.age );
printf("体重 = %3.1f\n", d.weight );
printf("身長 = %3.1f\n", d.height );
printf("---------------\n");
}
main()
{
DATA mydata = { "Deguchi", 40, 85.0, 170.0 };
prdata( mydata );
}
/* end of struct1.c */
/* 構造体のメンバを表示する関数2 */
#include <stdio.h>
#include <string.h>
typedef struct data
{
char name[20];
int age;
float weight;
float height;
} DATA, *Data;
/*
DATA は struct data 型
Data は struct data 型へのポインタ
*/
/* void prdata( struct data *dp ) と書いても良いが... */
void prdata( Data dp )
{
printf("名前 = %s\n", dp->name );
printf("年齢 = %d\n", dp->age );
printf("体重 = %3.1f\n", dp->weight );
printf("身長 = %3.1f\n", dp->height );
printf("---------------\n");
}
main()
{
DATA mydata = { "Deguchi", 40, 85.0, 170.0 };
prdata( &mydata );
}
/* end of struct2.c */
main()
{
DATA mydata;
/* 個々のメンバを設定する */
mydata.name = "Deguchi"; /* これは駄目! */
prdata( &mydata );
}
/* end of struct3.c */
/* 構造体の配列 */
#include <stdio.h>
#include <string.h>
typedef struct data
{
char name[20];
int age;
float weight;
float height;
} DATA, *Data;
/*
DATA は struct data 型
Data は struct data 型へのポインタ
*/
void prdata( Data dp )
{
printf("名前 = %s\n", dp->name );
printf("年齢 = %d\n", dp->age );
printf("体重 = %3.1f\n", dp->weight );
printf("身長 = %3.1f\n", dp->height );
printf("---------------\n");
}
main()
{
/* 構造体の配列の初期化 */
DATA ourdata[4] =
{
{ "山田太郎", 18, 80.0, 170.0 },
{ "鈴木健史", 17, 75.0, 175.0 },
{ "佐藤博司", 19, 90.0, 180.0 },
{ "", 0, 0, 0 }
};
int datanum = 3;
int i;
for( i = 0; i < datanum; i++ )
prdata( &ourdata[i] );
}
/* end of structa.c */