simple c++ help required!

AGD

AGD

Soldato
Joined
23 Nov 2007
Posts
5,048
Hi,

I've found a code to solve linear equations (Ax = b - all matrices/vectors) and need to get it running asap. I can understand all the bits inside the function but am having some trouble with the arguments. Am I correct in thinking the function takes the addresses of x and b as arguments? I don't know what the ** before the a means though.

Also can I just change the

#define eps 1e-10

to

const double eps?

Code:
#include <math.h>

#define EPS 1e-10

int gelimd2(double **a,double *b,double *x, int n)
{
    double tmp,pvt,*t,**aa,*bb;
    int i,j,k,itmp,retval;

    retval = 0;
    aa = new double *[n];
    bb = new double [n];
    for (i=0;i<n;i++) {
        aa[i] = new double [n];
        bb[i] = b[i];
        for (j=0;j<n;j++) {
            aa[i][j] = a[i][j];
        }
    }
    for (i=0;i<n;i++) {             // outer loop on rows
        pvt = aa[i][i];              // get pivot value
        if (fabs(pvt) < EPS) {
            for (j=i+1;j<n;j++) {
                if(fabs(pvt = aa[j][i]) >= EPS) break;
            }
            if (fabs(pvt) < EPS) {
                retval = 1;
                goto _100;     // pull the plug!
            }
            t=aa[j];                 // swap matrix rows...
            aa[j]=aa[i];
            aa[i]=t;
            tmp=bb[j];               // ...and result vector
            bb[j]=bb[i];
            bb[i]=tmp;        
        }
// (virtual) Gaussian elimination of column
        for (k=i+1;k<n;k++) {       // alt: for (k=n-1;k>i;k--)
            tmp = aa[k][i]/pvt;
            for (j=i+1;j<n;j++) {   // alt: for (j=n-1;j>i;j--)
                aa[k][j] -= tmp*aa[i][j];
            }
            bb[k] -= tmp*bb[i];
        }
	}
// Do back substitution
	for (i=n-1;i>=0;i--) {
        x[i]=bb[i];
		for (j=n-1;j>i;j--) {
            x[i] -= aa[i][j]*x[j];
		}
        x[i] /= aa[i][i];
	}
// Deallocate memory
_100:
    for (i=0;i<n;i++) {
        delete [] aa[i];
    }
    delete [] aa;
    delete [] bb;
    return retval;
}

Thanks.
 
* indicates a pointer... so ** is a pointer of a pointer :/ confusing I know.

Code:
aa = new double *[n];

As you can see **aa is now a pointer to a pointer with the above code.

With regards to #define... I guess you could. It's a compiler macro though rather than an actual variable, it's the compiler that replaces all references to it with the value in the code, it could be considered more efficient than storing the actual value in memory.
 
Last edited:
The syntax is confusing because of the way c++ allows you to interchange arrays and pointers to arrays interchangeably. A 2d array is an array of arrays, so you're passing a pointer to an array of pointers to arrays:

If you have int ** a, then a[0] has type int*, and is the first element of an array.
a[1] is an into pointer to the second array, etc etc.
 
Back
Top Bottom