Whenever I select the length of columns more than 3,it shows segmentation fault. It executes the code and shows no. of rows correctly but restricts the no. of columns to 3 only. '''
#include<stdio.h>
int main()
{
int i,j,r,c;
int arr1[r][c];
printf("Enter no. of rows in the array: ");
scanf("%d",&r);
printf("Enter no. of columns in the array: ");
scanf("%d",&c);
printf("Enter elements in %dX%d array:\n",r,c);
for ( i = 0; i < r; i++)
{
for ( j = 0; j < c; j++)
{
scanf("%d",&arr1[i][j]);
}
}
printf("Your entered array is:\n");
for ( i = 0; i < r; i++)
{
for ( j = 0; j < c; j++)
{
printf("%d ",arr1[i][j]);
}
printf("\n");
}
printf("Transpose of the array is:\n");
for ( i = 0; i < c; i++)
{
for ( j = 0; j < r; j++)
{
printf("%d ",arr1[j][i]);
}
printf("\n");
}
}
'''
Your first two lines of code in main()
are undefined behavior.
int i,j,r,c;
int arr1[r][c];
Neither r
nor c
are initialized, but you use them to create a 2d array arr1
. r
and c
will contain some garbage values which could be any integer. If they are negative or 0
, creating arr1
would fail. If they are positive but very large, creating arr1
could fail too.
After declaring your variables, you use scanf()
to initialize them, but the array is already created, so you need to switch the order. First create r
and c
, then get the user input from scanf()
and initialize them with it and then create the 2d array arr1
.