Originally Posted by
algorism
Oh, I see. (Pretty stupid of me not to notice that.)
In that case, you need to realloc based on c + m, not just m.
Augh, I am so stupid this is my previous code which had the realloc mistake. Could you kindly check this one instead:
Code:
#include <stdio.h>#include <stdlib.h>
struct poly
{
float exp;
float coeff;
}*arr,*add, temp;
int main(void)
{
int i,j,c=0,n,m,sum=0,k=0,f=0;
arr=NULL;
//INPUTTING POLYNOMIALS
printf("Enter no. of polynomials ");
scanf("%d", &n);
for (i=0;i<n;i++)
{
printf("Enter no. of terms in polynomial ");
scanf("%d", &m);
f+=m;
if (arr==NULL)
arr= (struct poly*)malloc(m*sizeof(struct poly));
else
arr= (struct poly*)realloc(arr, f*sizeof(struct poly));
for (j=0;j<m;j++)
{
printf("Enter coefficient: ");
scanf("%f", &arr[c].coeff);
printf("Enter exponent: ");
scanf("%f", &arr[c].exp);
c++;
}
}
//PRINTING
for (i=0;i<c;i++)
{
printf("%0.2fx^%0.2f +", arr[i].coeff, arr[i].exp);
}
//SORTING
for (i=0;i<c;i++)
for (j=0;j<c-1;j++)
{
if (arr[j].exp>arr[j+1].exp)
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
/*n=arr[j].exp;
arr[j].exp=arr[j+1].exp=arr[j].exp;
arr[j+1].exp=n;
m=arr[j].coeff;
arr[j].coeff=arr[j+1].coeff;
arr[j+1].coeff=m;*/
}
}
//PRINTING
for (i=0;i<c;i++)
{
printf("\n%0.2fx^%0.2f +", arr[i].coeff, arr[i].exp);
}
//ADDING
for (i=0;i<c;i++)
{
if (arr[i].exp == arr[i+1].exp) sum+=arr[i].coeff;
else {
add=(struct poly*)realloc(add,k*sizeof(struct poly));
add[k].coeff=sum+arr[i].coeff;
add[k].exp = arr[i].exp;
k++;
}
}
//PRINTING
for (i=0;i<k;i++)
{
printf("\n%0.2fx^%0.2f +", add[i].coeff, add[i].exp);
}
return 0;
}
As far as I think, my input should be working now. I think I mostly need help with the sorting and adding sections. (I am confused how my sorting works when I use a struct to swap them but stops working when I do it manually using two variables, I've put that part in comment section in the sorting area which didn't work)
Should I update the main post with the corrected code?
ED1 - Thanks again, I read through that horrible sorting re-assigning issue. So now I know why my struct swapping was working and not manual one. Also that code was outdated one, so I fixed my printf % signs as well. So far, inputting and sorting seems ok. (Thanks a lot :P) Now, I just need help with the addition issue. The addition part is in this code.