0

Can anybody please help to find an error in this code? I am not able to get the error, & its giving a Runtime error. I checked all loops used for matrix but not able to find an error.

    int  n, arr[n][n];
    cin>>n;
    for (i=0; i<n; i++)
    {
        for(j=0; j<n; j++)
        {
            cin>>arr[i][j];
        }
    }

    for (i=0; i<n; i++)
    {
        for(j=0; j<n; j++)
        {
            sum = 0;
            prev = ne;
            ne = 0;

            if(arr[i][j] == 1)
            {
                ne = i+j;
                prev = i+j;
                sum = ne - prev; 
                if(sum<0)
                    sum=-sum;
                steps+=sum;
            }           
            c++;
        }
    }
Kiran Malvi
  • 636
  • 2
  • 9
  • 29

2 Answers2

2

You are using variable n to create array without initializing it.You must always use a constant for initializing a static array

do something like this:

const int  n = SOME_VALUE;
int arr[n][n];
//rest remains same

also, you should use < n instead of <= n as pointed out by John.

if you want a dynamic array , then using STL vector will be better.

Community
  • 1
  • 1
mchouhan_google
  • 1,775
  • 1
  • 20
  • 28
0

You are not initialising the n variable and also your loop should be

for (i=0; i<n; i++)

Array indices in C++ start from zero

Same for the j loop

John Demetriou
  • 4,093
  • 6
  • 52
  • 88
  • Obi-Wan errors? hmm, I know of yoda expressions http://www.devsanon.com/2015/11/usefulness-of-yoda-expressions-in.html but Obi-Wan errors? never heard of those – John Demetriou Dec 08 '15 at 13:23