To clear confusion among the serveral problem the first one which invokes Undefined behavior in the code is, using uninitialized variable as VLA's size.
Also the for
loop logic is wrong and character input might create some problem the way it is handled. (when entered with \n
).
Correct code would be (considering that you don't want the whitespaces inputted into the array. Because if you do then there are other better choices like fgets
etc).
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 1024
int main(void)
{
int testcases;
int n_lines ,m_length;
int test, lines, length;
printf("Enter the no. of Test Cases ");
if( scanf("%d",&testcases) != 1){
fprintf(stderr, "%s\n","Error in input" );
exit(1);
}
if( testcases <= 0 ){
fprintf(stderr,"%s\n","Enter nonzero integer for testcases");
exit(1);
}
printf("%d",testcases);
for(test = 0; test < testcases; test++)
{
printf("Enter the lines and length of the test cases ");
if(scanf("%d%d",&n_lines,&m_length)!=1){
fprintf(stderr, "%s\n","Error in input" );
exit(1);
}
if( n_lines <= 0 || m_length <= 0 || !(n_lines <= MAXSIZE && m_length <= MAXSIZE)){
fprintf(stderr, "%s\n","Error in input n_lines and m_length" );
exit(1);
}
char n_m_matrix[n_lines][m_length];
for(lines = 0; lines < n_lines; lines++)
{
for(length = 0; length < m_length; length++)
{
if( scanf(" %c",&n_m_matrix[lines][length]) != 1)
{
fprintf(stderr, "%s\n","Eror in input" );
exit(1);
}
}
}
// work with VLA here.
}
return 0;
}
Here if you need much larger array sizes than this go for dynamic memory allocation. That will satisfy larger memory requirement in array.