|
이하의 소스에서 에러체크라고 써진데 매개변수및 링크를 위한 링크타입이 어떻게 되는지 알고싶습니다. 물론 이유까지 써주시면 고맙겠습니다.
매개변수로 주소를 보내주는동적할당은 잘못합니다.. 이해하기 쉽게 설명부탁드립니다.
#include<stdio.h>
#include<stdlib.h> // exit()
#include<malloc.h> // malloc()
#include<string.h> // memset()
#define IS_FULL(p) (!(p))
typedef struct _PTR ptr;
struct _PTR
{
float coef;
int exp;
ptr *link;
};
void attach(float coefficient, int exponent, ptr **txt) // error check
{
ptr *temp;
temp = (ptr *) malloc(sizeof(ptr));
memset(temp,0,sizeof(ptr));
if (IS_FULL(temp))
{
printf("We cannot attach new term since the memory is full\n");
return;
}
temp-> coef= coefficient ;
temp-> exp= exponent;
// 복잡하게 temp에 넣고 그것을 rear에다 대입한다.
(*txt)->link= temp; // error check
*txt= temp;
}
int compare(int exp1, int exp2)
{
if (exp1 = exp2)
return 0;
if (exp1 < exp2)
return -1;
else
return 1;
}
ptr* padd(ptr *p, ptr *q)
{
/* 함수내에서 rear변수는 정확하게 정해진 타입이 아님.
rear은 모두 error check*/
ptr *front, *rear, *temp;
float sum; // data type is float by recommend.
//rear = (ptr *) malloc(sizeof(ptr)); // rear is return value
//memset(rear,0,sizeof(ptr)); // return setting
if(IS_FULL(rear))
{
fprintf(stderr,"We cannot add two polynomials since the memory is full\n");
exit(1);
}
front = rear;
while ((p) && (q))
/* 다항식 P(x) 항의 차수와 Q(x)항의 차수를 비교 */
switch(compare(p->exp, q->exp))
{
case -1 :
attach( q->coef, q->exp, &rear);
q= q->link;
break;
/* 다항식 P(x) 항의 차수와 Q(x)항의 차수보다 적을 때
* Q(x)의 항을 하나 추가하고, 포인터 q가 다항식 Q(x)의
* 다음 항을 가리키도록 한다.
*/
case 0 :
sum = p->coef + q->coef;
if (sum)
attach(sum, p->exp, &rear);
p=p->link;
q=q->link;
break;
case 1:
attach(p->coef, p->exp, &rear);
p=p->link;
}
for(; p; p=p->link)
attach(p->coef, p->exp, rear);
for(; q; q=q->link)
attach(q->coef, q->exp, rear);
rear->link =NULL;
temp = front;
front = front ->link;
free(temp);
return &front;
}
void init(ptr **p, ptr **q)
{
ptr *w, *x, *y;
*p = (ptr *) malloc(sizeof(ptr));
*q = (ptr *) malloc(sizeof(ptr));
(*p)->coef = -3;
(*p)->exp = 5;
w=(ptr *) malloc(sizeof(ptr));
(*p)->link = w;
w->coef=2;
w->exp =2;
x =(ptr *) malloc(sizeof(ptr));
w->link = x;
x->coef=9;
x->exp =1;
y =(ptr *) malloc(sizeof(ptr));
x->link = y;
y->coef=-1;
y->exp =0;
y->link = NULL;
(*q)->coef = -2;
(*q)->exp = 5;
w=(ptr *) malloc(sizeof(ptr));
(*q)->link = w;
w->coef=3;
w->exp =3;
x =(ptr *) malloc(sizeof(ptr));
w->link = x;
x->coef=-4;
x->exp =2;
y =(ptr *) malloc(sizeof(ptr));
x->link = y;
y->coef=6;
y->exp =0;
y->link = NULL;
}
main()
{
ptr *p, *q, *r;
/* int *p라고 선언되었다면
* *p는 *p가 가리키는곳의 값
* p는 가리키는곳의 주소(값)
* &p는 현재 p의 주소.
*/
init(&p, &q);
printf("Data Init .. ok\n");
printf("Result Value Memory Allocation .. ok\n");
r=padd(p,q);
printf("Result Value Memory Insert .. ok\n");
while(r)
{
printf("%d ",r->coef,r->exp);
r=r->link;
}
printf("\n");
}
|