Write a program that reads an array of n polynomials and prints their squares using arrays.
Example input:

``````n=1
1. polynomial:
order: 2
coefficients: 1 1 1
``````

Output:

``````square(x^2+x+1)=2x^3+4x^2+2x+1
``````

The following code gives SIGSEGV segmentation fault:

``````#include <stdio.h>
#include <stdlib.h>
#define MAX_ORDER 10

typedef struct term
{
int coef;
int exp;
}TERM;

typedef struct
{
struct term arr[MAX_ORDER];
int terms;
}POLYNOMIAL;

void init(POLYNOMIAL *);
void square(POLYNOMIAL *poly,POLYNOMIAL *res);
void print(POLYNOMIAL *);

void init(POLYNOMIAL *poly)
{
int i;
poly->terms=0;
for(i=MAX_ORDER; i>=0; i--)
{
poly->arr[i].coef=0;
poly->arr[i].exp=0;
}
}

{
init(poly);
printf("order: ");
scanf("%d",&poly->terms);
printf("coefficients: ");
int i;
for(i=poly->terms; i >= 0; i--)
scanf("%d",&poly->arr[i].coef);
}

void square(POLYNOMIAL *poly,POLYNOMIAL *res)
{
init(res);
int i,j;
for(i=MAX_ORDER; i >= 0; i--)
{
for(j=MAX_ORDER; j >= 0; j--)
{
res->arr[i*j].coef=poly->arr[i].coef * poly->arr[j].coef;
res->arr[i+j].exp=poly->arr[i].exp + poly->arr[j].exp;
}
}
}

void print(POLYNOMIAL *poly)
{
int i;
for(i=poly->terms; i>=0; i--)
{
if(poly->arr[i].exp != 0)
printf("%dx^%d+",poly->arr[i].coef,poly->arr[i].exp);
else
printf("%d",poly->arr[i].coef);
}
}

int main()
{
int n,i;
POLYNOMIAL *arr,*res;
do
{
printf("n=");
scanf("%d",&n);
}
while(n < 1);
arr=(POLYNOMIAL*)malloc(n * sizeof(POLYNOMIAL));
res=(POLYNOMIAL*)malloc(n * sizeof(POLYNOMIAL));
for(i=0;i<n;i++)
{
printf("%d. polynomial: \n",i+1);
}
for(i=0;i<n;i++)
square(arr,res);
for(i=0;i<n;i++)
print(res);
free(res);
free(arr);
return 0;
}
``````

How to resolve this error?

Let's look at MAX_ORDER and your arrays.

So that's 10 and the array would be from index 0 to 9.

At line 28 and other places it looks like your code can use 10 as the index and get a fault.