![](/img/trans.png)
[英]gcc expect expression when I try to declare pointer and get it by malloc
[英]why does GCC “expect an expression”?
#define rows 2 #define cols 2 #define NUM_CORNERS 4 int main(void) { int i; int the_corners[NUM_CORNERS]; int array[rows][cols] = {{1, 2}, {3, 4}}; corners(array, the_corners); for (i = 0; i < 4; i++) printf("%d\n", the_corners[i]); } int corners (int array[rows][cols], int the_corners[]) { the_corners = { array[0][cols-1], array[0][0], array[rows-1][0], array[rows-1][cols-1] }; }
我收到这些奇怪的错误,我不知道为什么:
prog.c: In function ‘main’:
prog.c:10: warning: implicit declaration of function ‘corners’
prog.c: In function ‘corners’:
prog.c:15: error: expected expression before
您正在尝试使用初始化表达式作为赋值。 即使在 C99 中,这也是无效的,因为 the_corners 的类型是int*
,而不是int[4]
。 在这种情况下,您最好单独分配每个元素。
the_corners = {... }
语法是数组初始化,而不是赋值。 我手边没有标准的副本,所以我不能引用章节,但你想说:
void corners (int array[rows][cols], int the_corners[]) {
the_corners[0] = array[0][cols-1];
the_corners[1] = array[0][0];
the_corners[2] = array[rows-1][0];
the_corners[3] = array[rows-1][cols-1];
}
我还冒昧地将int corners
更改为void corners
,因为您没有返回任何东西。 而且您的main
还需要一个返回值,而您忘记了#include <stdio.h>
。
主要不知道你的 function。 要么将 function decleration 移到 main 上方,要么在 main 之前对其进行原型化:
int corners (int array[rows][cols], int the_corners[NUM_CORNERS]);
试试这个:
#include <stdio.h>
#define NROWS 2
#define NCOLUMNS 2
#define NCORNERS 4
int corners(int (*arr)[NCOLUMNS], int* the_corners);
int main() {
int i;
int the_corners[NCORNERS];
int arr[NCOLUMNS][NROWS] = {{1, 2}, {3, 4}};
corners(arr, the_corners);
for (i = 0; i < NCORNERS; i++)
printf("%d\n", the_corners[i]);
return 0;
}
int corners(int (*arr)[NCOLUMNS], int* the_corners) {
the_corners[0] = arr[0][NCOLUMNS-1];
the_corners[1] = arr[0][0];
the_corners[2] = arr[NROWS-1][0];
the_corners[3] = arr[NROWS-1][NCOLUMNS-1];
return 0;
}
您可以在此处阅读有关将二维数组传递给 function 的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.