|
このプログラムを共用体を用いるとどのようになるんですか。
一応共用体の定義だけできたのですがこのあとどうするのかが
よくわかりません。
もしよろしければ教えて下さい。
#include <stdio.h>
#include <stdlib.h>
typedef union {
int number;
double element;
} Vector;
int raedNumberofElements(int , char *[]);
void vectorSum(int, const double *, const double *, double *);
int main(int argc, char *argv[])
{
double *vectorA, *vectorB, *vectorC, *p_element;
int n, i;
n = raedNumberofElements(argc, argv);
if (n <= 0) {
return -1;
}
vectorA=(double *)malloc(n*sizeof(double));
vectorB=(double *)malloc(n*sizeof(double));
vectorC=(double *)malloc(n*sizeof(double));
p_element = vectorA;
printf("ベクトルaの各要素を入力して下さい\n");
for (i = 0; i < n; i++){
printf("ベクトルaの%d番目の要素: ", i + 1);
scanf("%lf", p_element);
p_element++;
}
printf("\n");
p_element = vectorB;
printf("ベクトルbの各要素を入力して下さい\n");
for (i = 0; i < n; i++){
printf("ベクトルbの%d番目の要素: ", i + 1);
scanf("%lf", p_element);
p_element++;
}
printf("\n");
vectorSum(n,vectorA,vectorB,vectorC);
p_element = vectorC;
printf("ベクトルの和を出力します\n");
for (i = 0; i < n; i++){
printf("和の%d番目の要素: ", i + 1);
printf("%10f\n", *p_element);
p_element++;
}
free(vectorA); vectorA = NULL;
free(vectorB); vectorB = NULL;
free(vectorC); vectorC = NULL;
return 0;
}
int raedNumberofElements(int argc, char *argv[])
{
int n;
if (argc <= 1) {
printf("引数がありません\n");
return -1;
} else if (argc >= 3) {
printf("引数が多すぎます。\n");
return -1;
} else {
n=atoi(argv[1]);
if (n <= 0) {
printf("1以上の整数を指定して下さい\n");
return -1;
}
return n;
}
}
void vectorSum(int n, const double *vectorA, const double *vectorB, double *vectorC)
{
int x=0;
while(x<n)
{
*vectorC=*vectorA+*vectorB;
vectorA++;
vectorB++;
vectorC++;
x++;
}
return;
}
1. 起動時にコマンドラインオプションとして整数を1つとりそれをベクトルの要素数とする。この値をnに代入する。
2. malloc() を使ってVector型のn+1個分のメモリーを2つ用意し、それぞれの先頭アドレスをvectorA, vectorB に入れる。
3. vectorAとvectorBの先頭に要素数を入れ、標準入力からn個の実数を2組読み込み vectorA と vectorB に順次格納する。
4. 関数 vectorSum() を呼び出してベクトルの和を計算する。
5. 計算結果を出力して終了する。
malloc() を使うときは必ず返り値がNULLでないことを確認すること。NULLのときはメモリの確保に失敗したなどと表示してプログラムを終了すること。
|