简体   繁体   中英

Return an Array from a function C: Subscripted value is not an array, pointer, or vector

I need to return the value of the matrix, but I am gettin this error

Subscripted value is not an array, pointer, or vector

in:

qk_output[m][o] = 0;

and

qk_output[m][o] += queries[m][n] * keys[n][o];

Could anyone help me? Thanks!

int* multmm(int queries[M][N], int keys[N][O]) {
  // Matrix Multiplication
  int* qk_output = (int*)malloc(sizeof(int) *M*N);
  for (int m = 0; m < M; m++) {

    for (int o = 0; o < O; o ++) {
      qk_output[m][o] = 0;

      for (int n = 0; n < N; n++) {
        qk_output[m][o] += queries[m][n] * keys[n][o];
      }
    }
  }
 return qk_output;
}
int* qk_output = (int*)malloc(sizeof(int) *M*N);

qk_output is a pointer to an int

the compiler knows how to access qk_output[n] but doesn't know how to access qk_output[m][n] , you need to switch to:

int (*qk_output)[N] = malloc(sizeof(*qk_output) * M); // Don't cast malloc

that is, a pointer to an array of N int s

Now the compiler has enough information to access qk_output[m][n]

For the return question: you can use void *multmm(...) or int (*multmm(...))[N] , the second one gives more information to the compiler so it is less error prone.

Something like:

int (*multmm(int queries[M][N], int keys[N][O]))[N]
{
    int (*qk_output)[N] = malloc(sizeof(*qk_output) * M);
    ...
    return qk_output;
}

int main(void)
{
    int (*arr2D)[N] = multmm(...);
    ...
}

To return a 2D array from a function, you can do

#define N 4
#define M 3

int (*foo(void ))[N]
{
    int (*p)[N] = malloc(M * sizeof *p);
    for (int i = 0; i < M; ++i)
    {
        for (int j = 0; j < N; ++j)
        {
            p[i][j] = i + j;
        }
    }
    return p;
}

int main (void){
    int (*mat)[N] = foo();
    
    for (int i = 0; i < M; ++i)
    {
        for (int j = 0; j < N; ++j)
        {
            printf("%d ", mat[i][j]);
        }
        puts("");
    }
    
    free(mat);
    return 0;   
} 

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