简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM