redeagle47
redeagle47

Reputation: 1377

invalid operands to binary * (have 'double *' and 'double *')

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?

Upvotes: 1

Views: 2068

Answers (2)

R Sahu
R Sahu

Reputation: 206577

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];

Upvotes: 2

Deduplicator
Deduplicator

Reputation: 45654

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);

Upvotes: 2

Related Questions