很抱歉,我问了一个已经回答过的问题,我是C的新手,不明白答案。
这是我的功能

int rotateArr(int *arr) {
    int D[4][4];
    int i = 0, n =0;
    for(i; i < M; i ++ ){
        for(n; n < N; n++){
            D[i][n] = arr[n][M - i + 1];
        }
    }
    return D;
}

它抛出了一个错误
main.c | 23 |错误:下标值既不是数组也不是
指针或矢量|
在线
D[i][n]=arr[n][M-i+1];
怎么了?我只是将一个数组元素的值设置为另一个数组元素。
通过的arr声明为
int S[4][4] = { { 1, 4, 10, 3 }, { 0, 6, 3, 8 }, { 7, 10 ,8, 5 },  { 9, 5, 11, 2}  };

最佳答案

C允许在数组和指针上使用下标运算符[]。在指针上使用此运算符时,结果类型是指针指向的类型。例如,如果将[]应用到int*,结果将是int
这正是发生的事情:您传递的是int*,它对应于一个整数向量。对它使用一次下标将使它int,因此不能对它应用第二个下标。
从代码中可以看出arr应该是一个二维数组。如果它被实现为一个“锯齿”数组(即指针数组),那么参数类型应该是int **
此外,似乎您正试图返回一个本地数组。为了合法地实现这一点,需要动态地分配数组,并返回一个指针。但是,更好的方法是为4x4矩阵声明一个特殊的struct,并使用它包装固定大小的数组,如下所示:

// This type wraps your 4x4 matrix
typedef struct {
    int arr[4][4];
} FourByFour;
// Now rotate(m) can use FourByFour as a type
FourByFour rotate(FourByFour m) {
    FourByFour D;
    for(int i = 0; i < 4; i ++ ){
        for(int n = 0; n < 4; n++){
            D.arr[i][n] = m.arr[n][3 - i];
        }
    }
    return D;
}
// Here is a demo of your rotate(m) in action:
int main(void) {
    FourByFour S = {.arr = {
        { 1, 4, 10, 3 },
        { 0, 6, 3, 8 },
        { 7, 10 ,8, 5 },
        { 9, 5, 11, 2}
    } };
    FourByFour r = rotate(S);
    for(int i=0; i < 4; i ++ ){
        for(int n=0; n < 4; n++){
            printf("%d ", r.arr[i][n]);
        }
        printf("\n");
    }
    return 0;
}

这个prints the following
3 8 5 2
10 3 8 11
4 6 10 5
1 0 7 9

08-18 14:04
查看更多