开发者

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 


The the_corners = { ... } syntax is an array initialization, not an assignment. 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. And your main also needs a return value and you forgot to #include <stdio.h>.


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]. In this case you would be best off assigning each element individually.


The main doesn' know about your function. Either move the function decleration above the main or prototype it before the 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜