Hello, I am trying to write a simple program where I want to find sum of polynomials. I've found out the my code is somewhere wrong during the sorting step using valgrind but I don't know why? Could anyone help me clear up my realloc basics?
Here's the full code:
Code:#include <stdio.h>#include <stdlib.h>
struct poly
{
float exp;
float coeff;
}*arr,*add;
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);
arr= (struct poly*)realloc(arr, m*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.2f x^0.2f +", arr[i].coeff, arr[i].exp);
}
//SORTING
for (i=0;i<c;i++)
for (j=0;j<c-i-1;j++)
{
if (arr[j].exp>arr[j+1].exp)
{
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);
}
return 0;
}