我在 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 函数也访问了未初始化的条目。
我认为 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);
}