I am a beginner in c, my goal is to add an array of polynomials, and for a few weeks I am really struggling to make this code to run properly, unfortunately there is an error due to the fact that I receive the error with the message "Unhanded exception" in the addition function at the result. I have been following this forum for several months and I want to thank you for all the answers that have been given on problems, they helped me a lot.
typedef struct
{
int* coef;
int exp;
}polinom;
typedef polinom* sir;
void read(polinom*,char); //read a polynom
void print(polinom,char*); //print a polynom
polinom addn(sir, int );
void read(polinom* p)
{
cout<<"Give the polynom "<<endl;
cout<<"\tgrad if polynom: ";
cin>>p->exp;
cout<<"\tGive coef:\n";
p->coef=(int*)malloc(sizeof(int)*((p->exp)+1));
for(int i=0;i<=p->exp;i++)
{
cout<<"\t\tcoef ["<<i+1<<"]= ";
cin>>p->coef[i];
}
}
void readn(sir r,int n)
{
for(int i=0;i<n;i++)
{
cout<<"Polynom ["<<i+1<<"]:\n";
read(&r[i]);
}
}
void print(polinom p)
{
for(int i=p.exp; i>=0; i--)
{
cout<<p.coef[i]<<'^'<<i<<' ';
}
cout<<endl;
}
void printn(sir r, int n)
{
cout<<"print a polynom\n";
for(int i=0; i<n; i++)
{
print(r[i]);
}
}
void main()
{
int n;
cout<<"Give a number of polynomials: \n";
cin>>n;
sir s;
s=(polinom*)malloc(sizeof(polinom)*n);
readn(s,n);
printn(s,n);
printf("here is the addition \n");
print(addn(s,n));
system("pause");
}
polinom addn(sir s, int n)//s array of polynomial and n is the number of them
{
int grad,i,j,k;
polinom result, aux;
for(i=0; i<10; i++)
{
aux.coef=0;
result.coef=0;
}//try to initialize
for(i=0; i<n; i++)
{
if(s[i].exp ==s[i+1].exp)//<---------------------x==y
{
for(j=0; j < s[i].exp; j++)
result.coef[j]=s[i].coef[j] + s[i+1].coef[j];
grad=s[i].exp;
}// end of if
if(s[i].exp > s[i+1].exp)//<---------------------x>y
{
for(j=0; j < s[i].exp; j++)
{
if(i >= s[i].exp-s[i+1].exp)
{
result.coef[j]=s[i].coef[j] + s[i+1].coef[j];
j++;
}// end of if
else
{
result.coef[j] = s[i].coef[j];
}// end of else
}
grad=s[i].exp;
}// end of if
if(s[i+1].exp < s[i].exp)//<---------------------y<x
{
for(j=0; j < s[i].exp; j++)
{
if(i >= s[i+1].exp-s[i].exp)
{
result.coef[j]=s[i].coef[j] + s[i+1].coef[j];
j++;
}// end of if
else
{
result.coef[j]=s[i].coef[j];
}// end of else
}
grad=s[i].exp;
}// end of if
if(i == n-1)//<---------------------only additional
{
result.exp=grad;
for(int k = 0; k < result.exp; k++)
{
aux.coef[k]=0;
result.coef[k] = result.coef[k] + aux.coef[k];
}
}
}
return result;
}