複素数を表す構造体 dcomplex を定義する。
#include<stdio.h>
struct dcomplex{
double re;
double im;
};
int main(void){
struct dcomplex z;
z.re = 3.0;
z.im = 1.0;
printf("z = %.1f + i%.1f\n", z.re, z.im);
}
typedef を使って簡便な表記のできる構造体を定義する。
構造体を引数と戻り値とする関数 dcplxConjugate を定義する。
#include<stdio.h>
/* use typedef to define structure */
typedef struct{
double re;
double im;
} dcomplex;
dcomplex dcplxConjugate(dcomplex x);
int main(void){
dcomplex z;
dcomplex w;
z.re = 3.0;
z.im = 1.0;
w = dcplxConjugate(z);
printf("z = %.1f + i(%.1f)\n", w.re, w.im);
return(0);
}
dcomplex dcplxConjugate(dcomplex x){
dcomplex z;
z.re = x.re;
z.im = -x.im;
return(z);
}
様々なデータ型を含んだ構造体を定義する。
#include<stdio.h>
#include<string.h>
typedef struct{
char name[50];
double height;
int age;
}person;
int printPerson(person p);
int main(void){
person a, b;
strcpy(a.name, "Barack Obama"); /* put string into a.name */
a.height = 185.0;
a.age = 52;
strcpy(b.name, "Hillary Clinton");
b.height = 169.0;
b.age = 66;
printPerson(a);
printPerson(b);
return(0);
}
int printPerson(person p){
printf("%s, %.1fcm, %d y.o\n", p.name, p.height, p.age);
return(0);
}