1

I tried to code a program in which the users can input a number of rows and columns in 2D matrix. It compiles without any errors but when I run the program, it does not work. After I input the number of rows, the program suddenly exits.

#include <cstdio>
typedef double** DMatrix;
DMatrix Matrix(int row, int col) {
    DMatrix x = new double* [row];
    for (int r=0; r<row; r++){
        x[r] = new double[col];
    }
    return x;
}

void Delete(DMatrix x, int row){
    for (int r=0; r<row; r++){
        delete[] x[r];
    }
    delete[] x;
}

int main (){
    int row , col;
    printf("Enter number of row : "); scanf("%d", row);
    printf("Enter number of column : "); scanf("%d", col);
    DMatrix A = Matrix(row, col);
    for (int i=0; i<row; i++){
        for (int j=0; j<col; j++){
            printf("Enter number in element %d%d :", i, j);
            scanf("%d\n", A[i][j]);
        }
    }
    for (int r=0; r<row; r++){
        for (int c=0; c<col; c++){
            printf("%lf\t", A[r][c]);
        }
        printf("\n");
    }
    Delete(A, row);
    return 0;
}
risingStark
  • 1,153
  • 10
  • 17
P.Chian
  • 65
  • 1
  • 7
  • You are missing `&` in `scanf()`. Read more, 1. https://stackoverflow.com/questions/18403154/when-should-i-use-ampersand-with-scanf 2. http://people.scs.carleton.ca/~mjhinek/W13/COMP2401/notes/scanf_printf.pdf 3. https://www.geeksforgeeks.org/use-scanf-not-printf/ – risingStark Aug 28 '21 at 08:26
  • *"After I input the number of rows, the program suddenly exits."* -- So you could trim your main function by removing everything after `printf("Enter number of column : ");`? (Keep that line to demonstrate that it is not reached, or simplify it to `printf("Rows were entered.");`.) If so, please do that, then remove the no-longer-needed pieces and update your question accordingly. (See [mre].) If the symptom is accurate, then you should discover that your question need not mention a 2D matrix. – JaMiT Aug 28 '21 at 08:53
  • Oh, I see. Thank you very much, your advice and link are helpful for me. – P.Chian Aug 28 '21 at 08:54

0 Answers0