Matthew Parker
Matthew Parker

Reputation: 55

Unhandled exception... Access violation writing location

I'm new to C++ and I'm trying to write a program that multiplies two arrays using double pointers. My code so far is:

        #include <iostream>
    using namespace std;

    //multiplies two matrices A(mxl) and B(lxn) to produce C(mxn)

    int m,l,n;
    int **A, **B, **C;

void main(void)
{

...user inputs m,l,n and allocates memory like this.

int i, j;

//creates a new mxl array   
A= (int**) new int*[m];
for(i=0;i<m;i++)
    {
        A[i]=new int[l];
    }

//creates a lxn array
B = (int**) new int*[l];
for(i=0;i<l;i++)
    {
        B[i]=new int[n];
    }

//creates a mxn array
C = (int**) new int*[m];
for(i=0;i<n;i++)
    {
        C[i]=new int[n];
    }

int sum = 0;
for(i=0;i<m;i++)
{
    for(j=0;j<n;j++)
    {
        for(int k=0;k<l;k++)
        {
            sum =+ A[i][k]*B[k][j];
        }
    }
      //cout<sum<<"\t";

so far everything works fine. If I change this to just cout 'sum' then it returns all the correct elements of the array in the right order; it's when I try to put this value into the array that it returns an error message.

    C[i][j]=sum; 
    }
}

I'm sure there's a much better way to multiply matrices together but I'm much more interested in knowing why this particular piece of code doesn't work; it looks very simple and I can't see where the error is coming from.

Upvotes: 4

Views: 3139

Answers (1)

David Heffernan
David Heffernan

Reputation: 612954

In your update you added this code:

C = (int**) new int*[m];
for(i=0;i<n;i++)
{
    C[i]=new int[n];
}

The loop condition is incorrect. Instead of i<n you need i<m.

Your multiplication loop looks like this:

for(i=0;i<m;i++)
{
    for(j=0;j<n;j++)
    {
        for(int k=0;k<l;k++)
        {
            sum =+ A[i][k]*B[k][j];
        }
    }
    C[i][j]=sum; 
}

The assignment C[i][j] is in the wrong block–the [j] array access is out-of-bounds.

It should be like this:

for(i=0;i<m;i++)
{
    for(j=0;j<n;j++)
    {
        sum = 0;
        for(int k=0;k<l;k++)
        {
            sum =+ A[i][k]*B[k][j];
        }
        C[i][j]=sum; 
    }
}

Note that I have initialised sum to 0 every time a new j loop is started. That corrects another error in your code.

It would be a lot better if you declared the variables with the tightest scope possible. Like this:

for(int i=0;i<m;i++)
{
    for(int j=0;j<n;j++)
    {
        int sum = 0;
        for(int k=0;k<l;k++)
        {
            sum =+ A[i][k]*B[k][j];
        }
        C[i][j]=sum; 
    }
}

Had you done that the compiler would have rejected your original placement of the assignment to C[i][j].

Your main function should be declared like this:

int main()

and you should return a value from your main().

Upvotes: 5

Related Questions