[英]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
qk_output
是一个指向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:编译器知道如何访问
qk_output[n]
但不知道如何访问qk_output[m][n]
,您需要切换到:
int (*qk_output)[N] = malloc(sizeof(*qk_output) * M); // Don't cast malloc
that is, a pointer to an array of N
int
s也就是说,一个指向
N
int
数组的指针
Now the compiler has enough information to access qk_output[m][n]
现在编译器有足够的信息来访问
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.对于返回问题:您可以使用
void *multmm(...)
或int (*multmm(...))[N]
,第二个为编译器提供更多信息,因此不易出错。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.