
Ubuntu 14.04.4 LTS で C コードを作成し、コンパイルしました。期待どおりに動作しています。ただし、Windows では実行されていますが、最終的には不適切な値が表示されます。
私が書いたコードは
#include <stdio.h>
#include <stdlib.h>
struct poly{
int coe[100];
};
void mul(struct poly *pr, int a, struct poly *p){
struct poly res;
int i;
for(i = 0; i < 100; i++){
res.coe[i] = 0;
int j;
for(j = 0; j <= i; j++){
res.coe[i] += ((*pr).coe[j])*((*(p + a)).coe[i - j]);
}
}
*pr = res;
}
void main(){
struct poly *p;
p = (struct poly *)malloc(100*sizeof(struct poly));
int n;
printf("no. of poly :");
scanf("%d", &n);
int i; int max = 0;
for(i = 0; i < n; i++){
int de;
printf("deg? of %d:", i+1);
scanf("%d", &de); max += de;
int j;
for(j = 0; j <= de; j++){
printf("co-eff of deg %d:", j);
scanf("%d", &p[i].coe[j]);
}
}
struct poly res;
struct poly *pr;
res = p[0];
pr = &res;
int fi;
for(fi = 1; fi < n; fi++){
mul(&res, fi, p);
}
for(i = 0; i < (max + 1); i++){
printf("%d\n", res.coe[i]);
}
}
そしてWindowsでの結果は次のようになります
C:\Users\Sai\Documents\C++>gcc ac.c -o ac
C:\Users\Sai\Documents\C++>ac
no. of poly :3
deg? of 1:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
deg? of 2:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
deg? of 3:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
1
3
6
85067032
255201082
510403447
-1897503563
C:\Users\Sai\Documents\C++>
Ubuntuの結果は
sai@sai-Inspiron-7548:~$ gcc ac.c -o ac
sai@sai-Inspiron-7548:~$ ./ac
no. of poly :3
deg? of 1:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
deg? of 2:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
deg? of 3:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
1
3
6
7
6
3
1
sai@sai-Inspiron-7548:~$
このプログラムを Windows 10 で正しく実行する方法。
私が書いたコードに何か問題がありますか。
ありがとう。
答え1
これは別の場所に投稿されるべきでしたが、解決策は次のとおりです。
必ず初期化してください。
coe[100]
内のすべての要素の配列を初期化していませんstruct poly*
。
ループでは一部のエントリのみを設定しますが、mul-function は初期化されていないエントリにもアクセスします。
Linux 上の gcc は、デフォルトで 0 として初期化することで何らかの方法でこれを処理していると思いますが、標準では初期化されていない整数の値は未定義として定義されています。
MinGW はそれを初期化しないので、その時点でメモリ内にあるものによって結果が台無しになります。
編集: もちろん、割り当てられたメモリもfree(p);
!で解放する必要があります。
修正方法は次のとおりです:
#include <stdio.h>
#include <stdlib.h>
struct poly{
int coe[100];
};
void mul(struct poly *pr, int a, struct poly *p){
struct poly res;
int i;
for(i = 0; i < 100; i++){
res.coe[i] = 0;
int j;
for(j = 0; j <= i; j++){
res.coe[i] += ((*pr).coe[j])*((*(p + a)).coe[i - j]);
}
}
*pr = res;
}
void main(){
struct poly *p;
p = (struct poly *)malloc(100*sizeof(struct poly));
for(int k = 0; k < 100; k++)
for(int l = 0; l < 100; l++)
p[k].coe[l] = 0;
int n;
printf("no. of poly :");
scanf("%d", &n);
int i; int max = 0;
for(i = 0; i < n; i++){
int de;
printf("deg? of %d:", i+1);
scanf("%d", &de); max += de;
int j;
for(j = 0; j <= de; j++){
printf("co-eff of deg %d:", j);
scanf("%d", &p[i].coe[j]);
}
}
struct poly res;
struct poly *pr;
res = p[0];
pr = &res;
int fi;
for(fi = 1; fi < n; fi++){
mul(&res, fi, p);
}
for(i = 0; i < (max + 1); i++){
printf("%d\n", res.coe[i]);
}
free(p);
}