try to get number of rows and column from user through array but it gives Segmentation fault at run time
#include<stdio.h>
int main(){
int rows;
int column;
int arr[rows];
int arr1[column];
printf("Enter the number of rows: ");
scanf("%d",&rows);
printf("Enter the number of column: ");
scanf("%d",&column);
printf("\n");
int i=0;
while( i<rows)
{ printf("\n");
printf("Enter the value of rows index: " );
scanf("%d",&arr[i]);
printf("\n");
i ;
}
int j=0;
while(j<column)
{
printf("Enter the value of rows index: " );
scanf("%d",&arr1[j]);
printf("\n");
j ;
}
}
// giving Segmentation fault
CodePudding user response:
At the time of your definition for the "arr" and "arr1" arrays, the value of column and rows is undefined.
int rows;
int column;
int arr[rows];
int arr1[column];
Move the declaration of those arrays after you have received input from the user.
printf("Enter the number of rows: ");
scanf("%d",&rows);
printf("Enter the number of column: ");
scanf("%d",&column);
printf("\n");
int arr[rows];
int arr1[column];
Give that a try and see if that addresses your segmentation fault.
CodePudding user response:
The program is giving segmentation fault because the array 'arr' and 'arr1' are declared before taking the input from user. The size of both arrays must be set before they are used.
To solve this issue, we need to declare the arrays after taking the input from user.
#include<stdio.h>
int main(){
int rows;
int column;
printf("Enter the number of rows: ");
scanf("%d",&rows);
printf("Enter the number of column: ");
scanf("%d",&column);
printf("\n");
int arr[rows];
int arr1[column];
int i=0;
while( i<rows)
{ printf("\n");
printf("Enter the value of rows index: " );
scanf("%d",&arr[i]);
printf("\n");
i ;
}
int j=0;
while(j<column)
{
printf("Enter the value of rows index: " );
scanf("%d",&arr1[j]);
printf("\n");
j ;
}
}