c언어 다항식의 덧셈 질문입니다.
Sonya
질문 제목 : c언어 다항식의 덧셈 질문입니다.질문 요약 :구조체와 파일입출력 등을 이용해서 코드를 짰는데 비쥬얼스튜디오로 돌려보면 계속 작동 중지만 뜨네요. 원인이 뭔지 모르겠어요. 돌아가려면 어떻게 해야할까요...... 포인터도 알맞게 쓴 것 같은데......질문 내용 : 아래 코드와 주석입니다.
#includestdio.h
#includestdlib.h
typedef struct
{
int exp; //지수
int coef; //가수
}poly;
int readpoly(const char*, poly**); // text file name을 받아 다항식 구조체에 저장
int padd(poly*, poly*, poly**, int, int); // 두 다항식을 더함
void printpoly(poly*,int); // 더한 다항식 구조체를 화면에 출력
int main()
{
poly *a, *b, *c;
int term_a, term_b, term_c;
term_a=readpoly(a.txt, &a);
term_b=readpoly(b.txt, &b);
term_c=padd(a,b,&c,term_a,term_b);
printpoly(c,term_c);
free(a);
free(b);
free(c);
return 0;
}
int readpoly(const char* filename, poly** p)
{
file *fp;
int exp, coef, term=0,i=0;
fp=fopen(filename, r);
if(!fp)
{
fprintf(stderr, file open error);
exit(1);
}
while(fscanf(fp, %d %d, &coef, &exp)!=eof)
{
term++;
}
fclose(fp);
p=(poly**)malloc(sizeof(poly*)*term);
fp=fopen(filename, r);
if(!fp)
{
fprintf(stderr, file open error);
exit(1);
}
while(fscanf(fp, %d %d, &coef, &exp)!=eof)
{
(*p)[i].exp=exp;
(*p)[i].coef=coef;
i++;
}
fclose(fp);
return term;
}
int padd(poly* a, poly* b, poly** c,int term_a, int term_b)
{
int start_a=0, start_b=0, sum_counter=0;
c=(poly**)malloc(sizeof(poly*)*(term_a+term_b));
// 더한 다항식의 항의 수 일단 a와 b의 항의 수를 더한 값을 넣음(c의 항의 수의 최댓값)
while(start_a = term_a-1 && start_b = term_b-1)
{
if(a[start_a].exp b[start_b].exp)
//a의 한 항의 지수가 b의 한 항의 지수보다 클 때, a의 항의 지수와 가수를 c항에 저장
{
(*c)[sum_counter].exp= a[start_a].exp;
(*c)[sum_counter].coef= a[start_a].coef;
++sum_counter;
++start_a;
}
else if(b[start_b].exp a[start_a].exp)
//b의 한 항의 지수가 a의 한 항의 지수보다 클 때, b의 항의 지수와 가수를 c의 항의 지수와 가수에 각각 저장
{
(*c)[sum_counter].exp= b[start_b].exp;
(*c)[sum_counter].coef= b[start_b].coef;
++sum_counter;
++start_b;
}
else
// a와 b의 각 항을 비교할 때, 지수가 같으면 c의 항의 지수에 a나 b항의 지수를, 가수에는 a와 b항의 가수를 더한 값을 저장
{
(*c)[sum_counter].exp= a[start_a].exp;
(*c)[sum_counter].coef= a[start_a].coef + b[start_b].coef;
++sum_counter;
++start_a;
++start_b;
}
}
return sum_counter;
}
void printpoly(poly c[],int n)
{
int i;
for(i=0;in;i++)
{
printf((%d,%d), , c[i].coef, c[i].exp);
if(i==n-1)
{
printf((%d,%d)\n, c[i].coef, c[i].exp);
}
}
}