gpt4 book ai didi

给数组元素赋值时,C下标值既不是数组也不是指针也不是 vector

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:38 25 4
gpt4 key购买 nike

很抱歉提出已经回答的问题,我是 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

关于给数组元素赋值时,C下标值既不是数组也不是指针也不是 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38821954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com