-2

I am getting a segmentation fault when running my program and also getting a weird result. I have put a lot of debug code in to find exactly where the weird behavior is.

int det_2b2(int d[2][2])
{
    cout<<d[1][1]<<","<<d[1][2]<<endl;
    cout<<d[2][1]<<","<<d[2][2]<<endl;
    cout<<(d[1][1]*d[2][2]-d[1][2]*d[2][1])<<endl;
     return (d[1][1]*d[2][2]-d[1][2]*d[2][1]);
}

int det_3b3(int d3[3][3])
{
    int r1;
    int x[2][2];
    x[1][1]=d3[2][2];
    x[1][2]=d3[2][3];
    x[2][1]=d3[3][2];
    x[2][2]=d3[3][3];
    cout<<"r1.1="<<det_2b2(x)<<endl;
    r1=det_2b2(x);
    cout<<"r1.2="<<r1<<endl;
    x[1][1]=d3[2][1];
    x[2][2]=35;
    cout<<"r1.3="<<r1<<endl;
    x[1][2]=d3[2][3];
    cout<<"r1.4="<<r1<<endl;
    x[2][1]=d3[3][1];
    cout<<"r1.5="<<r1<<endl;
    x[2][2]=d3[3][3];
    cout<<"r1.6="<<r1<<endl;
    int r2=det_2b2(x);
    x[1][1]=d3[2][1];
    x[1][2]=d3[2][2];
    x[2][1]=d3[3][1];
    x[2][2]=d3[3][2];
    int r3=det_2b2(x);
    cout<<r1<<endl;
    cout<<d3[1][1]<<endl;
    cout<<r1*d3[1][1]<<endl;
    cout<<r2*d3[1][2]<<endl;
    cout<<r3*d3[1][3]<<endl;
    return r1*d3[1][1]-r2*d3[1][2]+r3*d3[1][3];
}

When I set the value of x[2][2] = 35 or x[2][2]= d[3][3] it changes the value of r1 to 35 or to the value in d[3][3] so there is definitely something wrong under the covers. The calling program is

#include <iostream>
#include "utilities.h"

using namespace std;

int main()
{
    int a[3][3];
    a[1][1] =   1;
    a[1][2] =   2;
    a[1][3] =   3;
    a[2][1] =   4;
    a[2][2] =   5;
    a[2][3] =   6;
    a[3][1] =   7;
    a[3][2] =   8;
    a[3][3] =   9;
    cout << "DET a= " << det_3b3(a)<<endl;
    return 0;
}

The segmentation fault occurs at the end of the calling program well after the program error occurs.

Any ideas?

2 Answers2

2

Arrays in C++ are indexed from 0, not 1. Any access to a[x][3] in main, for example is out of bounds.

Just subtract 1 from all of your indices and it should compile, but you should read an introductory C++ book, and learn about loops and aggregate initialization.

Community
  • 1
  • 1
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
2

When you declare an array of size nXn, then the possible indices are from (0,0) to (n-1,n-1).

Therefore,

a[1][1] should be a[0][0], and so on.

So the last element would be a[2][2] (for 3 X 3 matrix), not a[3][3]

Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43