cdeclarationvariable-length-array

Asking user to input the sizes of 2D array C program


I'm coding a C program that asks the user to input two variables that represent the 2d array sizes and then print the array, I don't know where the problem is! any help?

`#include <stdio.h>
int main(void) {
int n, x, i, j;
int arr[n][x];
printf("Enter no of columns:");
scanf("%d", &n);
printf("Enter no of rows:");
scanf( "%d", &x);
printf("Enter elements: \n");
for (i = 0; i < n; i++)
for (j = 0; j < x; j++)
 scanf("%d", &arr[i][j]);
for (i = 0; i < n; i++){
  for (j = 0; j < x; j++)
  printf("%d \t", arr[i][j]);
  printf("\n");
}   
return 0;```
}``

Solution

  • You need to declare your variable length array arr after having initialized the variables you use to specify rows and columns. I also suggest naming the variables differently to not confuse readers.

    Example:

    #include <stdio.h>
    
    int main(void) {
        int rows, cols;
    
        printf("Enter no of columns:");
        if(scanf("%d", &cols) != 1 || cols < 1) return 1;
    
        printf("Enter no of rows:");
        if(scanf("%d", &rows) != 1 || rows < 1) return 1;
    
        int arr[rows][cols]; // declare it after rows and cols have been initialized
    
        printf("Enter elements: \n");
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < cols; j++) {
                if(scanf("%d", &arr[i][j]) != 1) return 1;
            }
        }
    
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < cols; j++) {
                printf("%d \t", arr[i][j]);
            }
            putchar('\n');
        }
    }