D
D
Dred Wolf2020-10-28 12:06:36
C++ / C#
Dred Wolf, 2020-10-28 12:06:36

How to solve the problem with the input of a two-dimensional array?

It is necessary to get the dimension of the array and its elements from the user.
When entering its elements, the following error occurs:
5f99344311fd6862007214.png
How to solve the problem? It is necessary to receive a matrix from the user, and then display it in the console (for further calculations).

CODE:

#include <stdio.h>
#include <locale.h>
#include <math.h>

int main()
{
    setlocale(LC_ALL, "Rus");
//row - строки, col - столбцы
    int row, col;

//Visual Studio не позволяет создать массив a[row][col], создаю a[1][1], чтобы потом переопределить
    int a[1][1];
    int i, j;

    printf("Число строк: ");
    scanf_s("%d", &row);

    printf("Число столбцов: ");
    scanf_s("%d", &col);

//переопределяю массив новыми размерами
    a[row][col];

    printf("Ввод матрицы \n");
    for (i = 0; i < row; ++i) {
        for (j = 0; j < col; ++j)
        {
            scanf_s("%d", &a[i][j]);
        }
    }

    return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2020-10-28
@Rsa97

//redefine the array with new sizes
a[row][col];
Why did you draw such a conclusion? It's just getting the value from the array a at row and col indexes.
Accordingly, your array remains 1x1 in size, and when writing to non-existent addresses, the stack is damaged.
How to solve the problem?
Learn how to create an array dynamically.

A
Alexander Ananiev, 2020-10-28
@SaNNy32

a[row][col];This is not an array redefinition, but an access to the element with indexes row and col.
To create a dynamic array, use pointers or std::vector.

W
Wataru, 2020-10-28
@wataru

As you've already been told, you're not allocating an array of the right size. Instead of int a[1][1], you can do int a[100][100], for example, if you know that the array will not be more than 100 rows and columns. But, for good, this must be processed and, if the user entered row == 101, then it must be completed, informing the user about the dimension being too large.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question