構造、定義してそれの例を宣言し、点表示法を使用しているメンバーに価値を割り当てることができる。 次の例は月の構造の使用を説明したものだ。
#include <stdio.h>
#include <string.h>
struct month
{
char name[10];
char abbreviation[4];
int days;
};
int main()
{
struct month m;
strcpy(m.name, "January");
strcpy(m.abbreviation, "Jan");
m.days = 31;
printf("%s is abbreviated as %s and has %d days\n", m.name, m.abbreviation, m.days);
return 0;
}
プログラムの出力は次の通りある:
January is abbreviated as Jan and has 31 days |
すべてのansiのCコンパイラは別のものに1つの構造を割り当てることを可能にしメンバー賢いコピーを行う。 m1と呼ばれた月の構造をおよびM2有したら、私達はm1からの次のM2に価値を割り当ててもよい:
- Structure with Pointer Members.
- Structure Initializes.
- Passing a Structure to a Function.
- Pointers and Structures.
cのポインターのメンバーが付いている構造
固定サイズ配列の保有物のひもは記憶の非能率的な使用である。 より有効なアプローチはポインターを使用することである。 ポインターは正常なポインター定義で使用される同じ方法で構造で丁度使用される。 私達を例を見ることを許可しなさい:
#include <string.h>
#include <malloc.h>
struct month
{
char *name;
char *abbreviation;
int days;
};
int main()
{
struct month m;
m.name = (char *)malloc((strlen("January")+1) *
sizeof(char));
strcpy(m.name, "January");
m.abbreviation = (char *)malloc((strlen("Jan")+1) *
sizeof(char));
strcpy(m.abbreviation, "Jan");
m.days = 31;
printf("%s is abbreviated as %s and has %d days\n",
m.name, m.abbreviation, m.days);
return 0;
}
プログラムの出力は次の通りある:
January is abbreviated as Jan and has 31 days |
|