How to populate a 2D array in C with custom input values?

Note. This is a homework question.

Use FOR construction to fill the 2D board with the values ​​that the user specified. The program asks for the board size n, m, and then asks for each board value.

My attempt

#include <stdio.h> int main(){ printf("Enter the number of columns"); int i = scanf("%d",&i); printf("Enter the number of rows"); int y = scanf("%d",&y); int r[i][y]; int a; int b; for (a=0; a<i; a++){ for(b=0; b<y; b++){ int r[a][b] = scanf("%d",&a,&b); //bug } } } 

Bug: c:13 variable-sized object may not be initialized

EDIT:

 #include <stdio.h> int main(){ printf("Enter the number of columns"); int i; scanf("%d", &i); printf("Enter the number of rows"); int y; scanf("%d", &y); int r[i][y]; int a; int b; for (a=0; a<i; a++){ for (b=0; b<y; b++){ scanf("%d",&r[a][b]); } } } 
+4
source share
5 answers

scanf takes the address of the variable that is being read and returns the number of elements read. It does not return the read value.

Replace

 int i = scanf("%d",&i); int y = scanf("%d",&y); 

by

 scanf("%d",&i); scanf("%d",&y); 

and

 int r[a][b] = scanf("%d",&a,&b); 

by

 scanf("%d",&r[a][b]); 

EDIT:

You use a variable length array (VLA) in your program:

 int r[i][y]; 

both i and y are not constants and are variables. VLA is a standard feature of the C99.

+7
source

you need to distribute the 2D array dynamically because you do not know its size in compilation.

replace

 int r[i][y]; 

with

 int *r = malloc(i*y*sizeof(int)); 

and when done add:

 free(r); 

* as well as SCANF errors, people have already answered here.

+2
source

At first, the return value of scanf not the value that was read from stdin ; instead, it reads the number of input scanf values.

Secondly, C does not allow you to create arrays using variables. You must first create one array by dynamically allocating it. And for each entry in the first array you need to create another array.

Do not forget to free the allocated memory!

+1
source

Using scanf(%d, &var) is wrong.
scanf reads an integer from the console (this type is specified by its first parasite %d ) and stores it in the second parameter .
This second parameter must be a pointer, so & is required when your variable is not already specified.

Therefore, you should fix your code as follows:

 int i; scanf("%d",&i); int y; scanf("%d", &y); 

And in your for loop

 scanf("%d", &r[a][b]); 
+1
source

It does not display a message due to line buffering.

If you add \n to your lines (to start a new line), it can do what you expect:

 printf("Enter the number of columns\n"); 

Alternatively, if you really want the user to print on the same line, you need to manually reset the buffer:

 printf("Enter the number of columns"); fflush (stdout); 
0
source

Source: https://habr.com/ru/post/1382256/


All Articles