Kiran Malvi
Kiran Malvi

Reputation: 636

SIGSEGV Error (Probably Array Index Out Of Bound)

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++;
        }
    }

Upvotes: 0

Views: 73

Answers (2)

mchouhan
mchouhan

Reputation: 1873

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.

Upvotes: 2

John Demetriou
John Demetriou

Reputation: 4371

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

Upvotes: 0

Related Questions