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

167 Views Asked by At

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;```
}``
2

There are 2 best solutions below

2
Ted Lyngmo On BEST ANSWER

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');
    }
}
0
Vlad from Moscow On

This declaration of the array

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);
//...

has undefined behavior because the variables n and x are not initialized. You need to declare the array after entering values to the variables.

Also in the array declaration rows should precede columns.

That is you need at least to write

int n, x, i, j;
printf("Enter no of columns:");
scanf("%d", &n);
printf("Enter no of rows:");
scanf( "%d", &x);
int arr[x][n];
//...

And you need to check that entered values are positive.

Pay attention to that you should declare variables in minimum scopes where they are used.