Using Pointers and Arrays to Solve the Linear System

advertisements

I've been assigned a problem that asks us to solve a 2 equation system using an array and a pointer to that array. It's sort of a linear algebra way of going about it, with x_1 = (DE-BF)/(AD - BC) and x_2 = (AF - CE)/(AD - BC). The system is Ax_1 + Bx_2 = C and Dx_1 + Ex_2 = F. My code compiles fine but spits out garbage. Can anyone help me? I'm sure it's an error with my pointers but I don't know how to correct it. Much thanks in advance.

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

using namespace std;

int main(){
    double A,B,C,D,E,F;
    cout << "Please enter a value for A: " << endl;
    cin >> A;
    cout << "Please enter a value for B: " << endl;
    cin >> B;
    cout << "Please enter a value for C: " << endl;
    cin >> C;
    cout << "Please enter a value for D: " << endl;
    cin >> D;
    cout << "Please enter a value for E: " << endl;
    cin >> E;
    cout << "Please enter a value for F: " << endl;
    cin >> F;
    double paramarray[6] = {A,B,C,D,E,F};
    double* p;
    p = &paramarray[6];
    double x1 = (p[3]*p[4] - p[1]*p[5])/(p[0]*p[3] - p[1]*p[2]);
    double x2 = (p[0]*p[5] - p[2]*p[4])/(p[0]*p[3] - p[1]*p[2]);
    cout << "X_1 = " << x1 << endl;
    cout << "X_2 = " << x2 << endl;
    int f;
    cin >> f;
    return 0;
}


p = &paramarray[6];

This is the problem. This means you are assigning the address of paramarray[6] to p. paramarray[6] is not defined and you are trying to access out of bounds array.

Try changing it to

p = paramarray;

Also, it will be better if you first check for zero denominator and update your equation accordingly.