Aravind Prakash Aravind Prakash - 1 month ago 12
C Question

C program throws a runtime error

#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,k,n,q;
scanf("%d%d%d",&n,&k,&q);
int *m=malloc(5*sizeof(int));
int **a=malloc(20*sizeof(int));
//int a[10][10],m[10];
for(i=0;i<k;i++)
a[i]=malloc(sizeof(int));
for(i=0;i<n;i++)
{scanf("%d",&a[0][i]);}
for(i=0;i<q;i++)
{scanf("%d",&m[i]);}
for(i=0;i<k;i++)
{
for(j=0;j<n;j++)
{
if(j==(n-1)) a[i+1][0]=a[i][j];
else
a[i+1][j+1]=a[i][j];
}

}
for(i=0;i<q;i++)
printf("%d\n",a[k][m[i]]);
return 0;
}


I tried this code in codeblocks but it seems that it doesn't accept any values after I enter the values of
m[]
.

The error is: "matright.exe has stopped working".
The input that i entered was :
3 2 3
1 2 3
0
1
2

Answer

The second malloc

int **a=malloc(20*sizeof(int));

should be

int **a=malloc(20*sizeof(int*));

The third malloc

a[i]=malloc(sizeof(int));

only allocates memory for one element, yet you follow this with a n loop.

Edit (from TobySpeight):

Also, the array lengths have been hard coded. Guessing from the loops further down, you should be allocating:

int *m = malloc(q * sizeof(int));
int **a = malloc(k * sizeof(int*));

with the third one as

a[i] = malloc(n * sizeof(int));