Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a 2D array in C with user input values?

Tags:

arrays

c

Note: This is a homework question.

Use FOR construction to fill 2D board with values that were given by user. The program asks for board size n, m and then it asks for each board value.

My try

#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]);
        }
    }
}
like image 254
user1050014 Avatar asked Dec 21 '22 06:12

user1050014


1 Answers

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

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 are using variable length array (VLA) in your program:

int r[i][y];

as i and y are not constants and are variables. VLA are a C99 standard feature.

like image 151
codaddict Avatar answered Dec 24 '22 01:12

codaddict