0

I have a program that multiplies matrices sequentially in C that I'm trying to finish up. I'm getting the error listed in the title.

Here is the line that is giving me the trouble:

C[i,j] = C[i,j] + A[i,k] * B[k,j];

A, B, and C are 2-dimensional arrays. They are defined with this code:

A = (double **) malloc(sizeof(double *)*n);
for (r = 0; r < n; r++) {
  A[r] = (double *) malloc(sizeof(double)*n);
}

The definition of B and C are the same as this. n is an integer value which defines the size of the columns and rows.

I don't know why I'm getting this error. From some of the other questions I've looked at, this error comes up when the types for an operation are incorrect, but I don't understand why that's the case here. Does anyone have any ideas?

redeagle47
  • 1,355
  • 4
  • 14
  • 26

2 Answers2

3

There is no multi-index indexing-operator in C.

What you have is actually single-indexing with an expression which contains the comma-operator.

The comma-operator always returns its second argument.

So, use normal indexing twice instead of trying to cram a second index in there somehow.

C[i,j] = C[i,j] + A[i,k] * B[k,j];

Is equivalent to:

C[j] = C[j] + A[k] * B[j];

Not to what you seem to want:

C[i][j] = C[i][j] + A[i][k] * B[k][j];

As an aside, Don't cast the result of malloc (and friends):

A = (double **) malloc(sizeof(double *)*n);

should be the less error-prone:

A = malloc(n * sizeof *A);
Community
  • 1
  • 1
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • I think I must have copied that over from the algorithm I was looking at. Thank you for your help. – redeagle47 Nov 05 '14 at 18:53
  • Yes, those pseudo-code algorithm normally use more mathematical notation. Also, you are a step up from most if you really read such things. – Deduplicator Nov 05 '14 at 18:56
2

C[i,j] is equivalent to C[j]. i,j in this context is treated as a comma operator whose value is the last expression.

Instead of

C[i,j] = C[i,j] + A[i,k] * B[k,j];

use

C[i][j] += A[i][k] * B[k][j];
R Sahu
  • 204,454
  • 14
  • 159
  • 270