classic_man
classic_man

Reputation: 45

Pointer to multidimensional array error: Expression must have pointer-to-object type

The following code returns the error: Expression must have pointer-to-object type. somehow the problem lies in the way I reference the parameters A, B and out which each point to a 2D array. Any help would be much appreciated.

The goal is to multiply two arrays.

#include <stdio.h>

void matrixmul(const float *A, const float *B, int m, int n, int k, float *out)
{
    float value = 0.0;

    int x, y, z;

    for (x = 0; x < k; x++) {
        for (y = 0; y < m; y++) {
            for (z = 0; z < n; z++) {

                    float product = A[y][z] * B[z][y];
                    value = value + product;
                    printf("%lf", value);
                }
                out[y][x] = value;
                value = 0;
            }
        }
    }

    int main(void) {
        float a[2][3] = {
            { 1.0,2.0,1.0 },
            { 3.0,4.0,1.0 }
        };


        float b[3][1] = {1, 2, 3};

        float array[2][1]; 
        matrixmul((float *) a, (float *) b, 2, 3, 1, (float *) array);
        return 0;
    }

Upvotes: 1

Views: 1041

Answers (2)

R Sahu
R Sahu

Reputation: 206737

Since A is declared as const float *A in the function, A[y][z] is an invalid term. A[y] evaluates to type const float. You can't use an array operator, [z], with a float.

The same problem occurs with B and out.

You can define the function as

void matrixmul(const float A[][3], const float B[][1], int m, int n, int k, float out[][1])
{
  ...
}

and call the function simply as:

matrixmul(a, b, 2, 3, 1, array);

C99/C11 support variable length arrays. Assuming you can use compiler that supports C99/C11, you can define the function as

void matrixmul(int arows, int acols, int bcols,
               const float A[arows][acols],
               const float B[acols][bcols],
               float out[arows][bcols])
{
  ...
}

and call the function using

matrixmul(2, 3, 1, a, b, array);

Upvotes: 1

Christian Gibbons
Christian Gibbons

Reputation: 4370

The function does not know the dimensions of your array, so it does not know how to calculate the address of a value given the row and column. You can use a function's arguments to define the dimensions of your matrix, however. You will have to rearrange the arguments in your function such that the arguments specifying the dimensions appear before the array. Using your function, it might look something like this:

void matrixmul(int m, int n, int k, const float A[m][n], const float B[n][m], float out[m][k])

By the way, I haven't really read fully through the function, but is out[y][k] = value; supposed to be out[y][x] = value;?

Upvotes: 0

Related Questions