I wrote a program to generate monomials and polynomial and print monomials and polynomial. The data are input from keyboard. For example, first input the number of groups of data 3, then input the data: 1,3,2,4,3,6,3,4,2 (each group has 3 elements). I need output monomial Y^{1}{2,3}Y^{4}{3,6}Y^{3}_{4,2}. My program can work. But the output is not correct. I think the problem of the program is in the following part. I think the scanf is not good in the following. Are there other better input method to fix this problem? The whole program is in http://hi.baidu.com/lijr03/blog/item/51e17b0c63614bc863d98629.html
monomial create_monomial(int number) /* create a monomial */
{
monomial m,s;
monomial p;
int i;
printf("Please input the parameters (for example, 2, 2, 3 denotes the monomial P^{2}_{2,3}). The first subscripts i's of P's should be in increase order.");
m=(monomial)malloc(sizeof(monomial_node));
m->head=m->tail=(monomial)malloc(sizeof(monomial_node));
if(m->head==NULL)
{
return NULL;
}
m->head->next=m->tail;
m->tail->next=NULL;
p=(monomial)malloc(sizeof(monomial_node));
m->head->next=p;
p->next=m->tail;
scanf("%d", &((p->y).l));
scanf("%d", &((p->y).i));
scanf("%d", &((p->y).k));
if(number > 1)
{
for(i=0;i<number-1;i++)
{
s=(monomial)malloc(sizeof(monomial_node));
scanf("%d", &((s->y).l));
scanf("%d", &((s->y).i));
scanf("%d", &((s->y).k));
s->next=p->next; /* insert the node a */
p->next=s;
free(s);
}
}
return m;
}
The
free(s)means that you are destroying the monomial that you’ve just created. The pointer that you create above it (fromp) means that you’ll be pointing to a potentially invalid bit of memory when you processm.