[英]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] }; }
I get these weird errors and i have no idea why:我收到这些奇怪的错误,我不知道为什么:
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
You're trying to use an initialiser expression as an assignment.您正在尝试使用初始化表达式作为赋值。 This isn't valid, even in C99, because the type of the_corners is int*
, not int[4]
.即使在 C99 中,这也是无效的,因为 the_corners 的类型是int*
,而不是int[4]
。 In this case you would be best off assigning each element individually.在这种情况下,您最好单独分配每个元素。
The the_corners = {... }
syntax is an array initialization, not an assignment. the_corners = {... }
语法是数组初始化,而不是赋值。 I don't have a copy of the standard handy so I can't quote chapter and verse but you want to say this:我手边没有标准的副本,所以我不能引用章节,但你想说:
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];
}
I also took the liberty of changing int corners
to void corners
as you weren't returning anything.我还冒昧地将int corners
更改为void corners
,因为您没有返回任何东西。 And your main
also needs a return value and you forgot to #include <stdio.h>
.而且您的main
还需要一个返回值,而您忘记了#include <stdio.h>
。
The main doesn' know about your function.主要不知道你的 function。 Either move the function decleration above the main or prototype it before the main:要么将 function decleration 移到 main 上方,要么在 main 之前对其进行原型化:
int corners (int array[rows][cols], int the_corners[NUM_CORNERS]);
Try this one:试试这个:
#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;
}
You can read here about passing a 2D array to a function.您可以在此处阅读有关将二维数组传递给 function 的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.