0

Can anyone explain to me why I get a segmentation fault here?

(I'm writing a longer program that involves adding and multiplying matrices saved as dynamic arrays, but I tried to narrow down the scope of the program looking for the error - so don't worry that the excerpt below doesn't make too much sense, I just want to know what is wrong syntactically with it.)

int
main (void)
{
    int* a;
    int* c;
    int i,j,d;
    int n = 3;
    int m = n*n;
    a = (int*)malloc(m*sizeof(int));
    c = (int*)malloc(m*sizeof(int));
    a[0] = 1; a[1] = 4; a[2] = 3; a[3] = 2; a[4] = 2; a[5] = 2; a[6] = 0; a[7] = 1;
    a[8] = 0;

for (i = 0; i<n; ++i)
    {
    for (j = 0; i<n; ++j)
        {
        d = i*n + j;
        c[d] = a[d] + a[d];
        }
    }


 return 0;
}
0

2 Answers 2

2

Second loop should use j not i in the terminating condition:

for (j = 0; i<n; ++j)
            ^

should be

for (j = 0; j < n; ++j)
Sign up to request clarification or add additional context in comments.

Comments

1

In your second loop you have the wrong conditional:

for (j = 0; i<n; ++j)

should be

for (j = 0; j<n; ++j)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.