Home > database >  Array doesn't print correct values beyond a certain limit of indices
Array doesn't print correct values beyond a certain limit of indices

Time:06-25

The following code gives a very wrong and random output for inputs greater than 5,5 (respective values of m and n wrt the code below). Why is it so? What might be the fix to this?

#include <bits/stdc  .h>
using namespace std;

int main()
{

    int t;
    cin>>t;
    while(t--)
    {
        int m,n;

        cin>>m>>n;

        int i,j,k;
       int a[m][n];
       k = 1;
      a[0][0] == 1;

       for(i=0;i<m;i  ){
        
        for(j=0;j<n;j  ){
            cout<<(a[0][0] k*(j 1))<<" ";
        }
        
        k = k 2;
        cout<<'\n';
       }
    
    }
    return 0;
}

CodePudding user response:

If you compile this withg warnings enabled you get:

<source>:18:15: warning: equality comparison result unused [-Wunused-comparison]
      a[0][0] == 1;
      ~~~~~~~~^~~~
<source>:18:15: note: use '=' to turn this equality comparison into an assignment
      a[0][0] == 1;
              ^~
              =
1 warning generated.

You don't want comparison there but a[0][0] = 1;.


Now for other stuff you shouldn't do:

  • int a[m][n]; is not C but a compiler extension. Use std::vector.
  • int a[m][n]; leaves the array uninitialized and you only ever write to a[0][0] (if you fix the ==).
  • a is never ever used except for a[0][0]. The whole array is utterly pointless. A single const int a = 1; would do the same.
  • #include <bits/stdc .h> is wrong and doesn't even exist on many compilers
  • using namespace std; is overly broad. You never want/need all of std. Be more selective.
  •  Tags:  
  • c
  • Related