Question


This code executed successfully in Visual C++, but showed run time error in Code Blocks returning "Process terminated with status -1073741819". Also when MAX is defined as "#define MAX 4" it executed successfully. Can anyone please help? Thanx!


#include <iostream>
#include <cstdlib>
#define MAX 32              

using namespace std;

double **A, **B, **C;

void initialize(double** x)     //code to initialize matrix
{
static int n = 0;

for(int i = 0; i < MAX; i++)
    *(x+i) = (double*) new double[MAX];

srand(n);
double* ptr = *x;

for(int i = 0; i < MAX; i++)
    for(int j = 0; j < MAX; j++)
    *(ptr+(i*MAX)+j) = rand() % 100;

n++;
}

void print(double** x)
{
double* ptr = *x;

for(int i = 0; i < MAX; i++){
    for(int j = 0; j < MAX; j++)
    cout<<*(ptr+(i*MAX)+j)<<"  ";
    cout<<endl;
}
}

int main(){
A = (double**) new double[MAX];
B = (double**) new double[MAX];
C = (double**) new double[MAX];

initialize(A);
initialize(B);
initialize(C);

print(A);
cout<<endl;
print(B);
cout<<endl;
print(C);
cout<<endl;
system("pause");
return 0;
}
Was it helpful?

Solution

In place of "*(ptr+(i*MAX)+j)" to access x[i,j] use " * ( *(x+i)+j) " .

This will resolve the segmentation fault. "*(ptr+(i*MAX)+j)" is same as ptr[i*MAX+j] which is an out-of-bounds access for some values of i and j.

OTHER TIPS

your variables should be double *, not double ** (pointers to pointers).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top