0

So I am a Beginner in C and I was going through Arrays and i was having success with arrays restricted to bounds of constant integers... But i also wanted to find out what happens if we give in a random number for the Numbers of Rows and columns.. However when i executed the program all was fine until the 4th element wherein Vscode with display an error message of Matrix.exe(The compiled file) not working.. I somehow guessed that the error was with vscode itself..(i might be horribly wrong) So i went for an online compiler and didnt get the desired result..which was received easily with bounded constant integers..

The code is about treating a two dimensional array as a Matrix and then getting the desired result in a table form i.e to get a print of all the elements in a tabular form. I will post the code now:

`

#include<iostream>
  using namespace std;
  int main()
  {
    int m,n;
    int matrix[m][n];
    cout<<"Please give the number of Rows:";
    cin>>m;
    cout<<"Please give the number of columns:";
    cin>>n;
    for (int i=0;i<m;++i)
    {
        for (int j=0;j<n;++j)
        {
            cout<<"Please enter matrix element:";
            cin>>matrix[i][j];
        }
     }
     //printingmatrix
     cout<<"The Matrix is:";
     for (int a=0;a<m;a++)
     {
        for (int b=0;b<n;b++)
        {
           cout<<matrix[a][b]<< "   ";
        }
        cout<<endl;
      }
  }`

I dont actually know what the problem is the code might be incorrect but seemed logically correct to me... I actually dont have any idea of why i am not receiving the result!

Also this is my first stack ques so sorry if I sucked at asking! ;) Any help will be appreciated! Thanks!

  • Array size must be known by the run-time. It's a fundamental principle of arrays in strong type languages. You may use linked list, though. – bimjhi May 20 '21 at 21:31
  • Runtime variables for array indices are not C++ -- these are VLAs (variable-length arrays), which are a non-standard extension to C++. Also, you can't use an uninitialized `int` for that either -- that is undefined behavior. – Human-Compiler May 20 '21 at 21:31
  • Thank you all! I shall not use uninatialised variables...Will keep that in my memory Thanks! ;) – The_Osprey May 20 '21 at 21:39
  • visuakl studio tells e that `int matrix[m][n]`can't be done , because the dinmenssion must be a constant, and determined beforehand. you should try iot with lists instead – nbk May 21 '21 at 11:20

3 Answers3

1
int m,n;
int matrix[m][n];

There are two big problems here.

Problem 1: You don't give any value to m nor n. Then you use these ungiven values as the size of an array. C++ is not a "dataflow" language. If you use a value, the program won't stop, and wait for you to initialise the value later. If you use an uninitialised value, then the behaviour of the program will be undefined. There are exceptions, but none that apply to this case, so the behaviour of your program is undefined. That is something to avoid. Solution: Don't ever use uninitialised values.

Problem 2: The values that you later give are not compile time constant. The size of an array variable must be compile time constant in C++. The program is ill-formed. Solution: If you need an array with runtime size, then you must allocate it dynamically. The simplest solution is to use std::vector provided by the standard library.

So I am a Beginner in C

Note that C and C++ are two distinct languages.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Thank you for the response! I guess we learn sure i will not use uniniatialised variables from now! as for the vector part since i am a beginner i am not introduced to vectors...The program is ill formed i agree but i gave my best shot without vectors! I should go on to learn about vectors too! Thank you for the response It helped me! :) – The_Osprey May 20 '21 at 21:35
  • @The_Osprey insted of using vector you can allocate the array using `new`. http://www.cplusplus.com/doc/tutorial/dynamic/ – Ido May 20 '21 at 21:41
  • 1
    @Ido In general that's a pretty bad idea, though. One imposes all the memory management, pointer handling, etc on the programmer that would otherwise be handled by the vector already. There might be special cases for which `std::vector` appears less suitable, but then one should first check if possibly other containers are better suited (`std::deque`, `std::set`, `std::list`, ...). Only if all of these don't provide a suitable solution one should come up with her/his own one. – Aconcagua May 25 '21 at 05:34
1

In addition to @eerorika's answer, if you want to have a modern solution to your problem you can use std::vector<std::vector<int>> to have a dynamic 2d array.

  • A std::vector can be resized by simply calling .resize(n).

  • A std::vector stores the length, get it by calling .size()

  • An element inside a vector can be accessed via []

With this information, you can rewrite your code to look like this:

#include <iostream>
#include <vector>

int main() {

    int m, n;
    std::cout << "Please give the number of Rows: ";
    std::cin >> m;
    std::cout << "Please give the number of columns: ";
    std::cin >> n;

    std::vector<std::vector<int>> matrix;
    matrix.resize(m);
    for (int i = 0; i < matrix.size(); ++i) {
        matrix[i].resize(n);
    }

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            std::cout << "Please enter matrix element [" << i << ", " << j << "] : ";
            std::cin >> matrix[i][j];
        }
    }

    std::cout << "The Matrix is:\n";


    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            std::cout << matrix[i][j] << " \t";

        }
        std::cout << '\n';
    }
}

Example run:

Please give the number of Rows: 3
Please give the number of columns: 2
Please enter matrix element [0, 0] : 0
Please enter matrix element [0, 1] : 5
Please enter matrix element [1, 0] : -3
Please enter matrix element [1, 1] : 11
Please enter matrix element [2, 0] : 20
Please enter matrix element [2, 1] : 99
The Matrix is:
0       5
-3      11
20      99

  • You can read here why using namespace std; is considered bad practice.

  • Read about range-based for loop to learn more on how to use std::vector in a modern approach.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
0

The problem with your original code is that C++ does not allow you to declare or initialize arrays with non-constant values for dimensions.

You can easily fix this issue if you use C++ STL vector as shown in the code below:

First, please note that you will need to include the header vector

Second, please see how I instantiate the vector matrix as a 2D array in the code. And, I also removed one line of your old code, and instead added the declaration for the vector matrix.

#include<iostream>

#include<vector>    // This line must be added to use STL vector

using namespace std;

  int main()
  {
    int m,n;

    //int matrix[m][n];   // I removed this line

    cout<<"Please give the number of Rows:";
    cin>>m;
    cout<<"Please give the number of columns:";
    cin>>n;

    vector<vector<int>> matrix(m, vector<int>(n, 0) ); // I added this line

    for (int i=0;i<m;++i)
    {
        for (int j=0;j<n;++j)
        {
            cout<<"Please enter matrix element:";
            cin>>matrix[i][j];
        }
     }
     //printingmatrix
     cout<<"The Matrix is:";
     for (int a=0;a<m;a++)
     {
        for (int b=0;b<n; b++)
        {
           cout<<matrix[a][b]<< "   ";
        }
        cout<<endl;
      }
  }

Note: I have tested and verified the code above run well. Please let me know if you have any issue.

Job_September_2020
  • 858
  • 2
  • 10
  • 25