很抱歉提出已经回答的问题,我是 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|error: subscripted value is neither array nor pointer nor vector|
在线
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*
,它对应于一个整数 vector 。在其上使用一次下标使其成为 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
我是一名优秀的程序员,十分优秀!