问题描述
很抱歉询问已经回答的问题,我是C的新手,不了解解决方案.这是我的功能
Sorry for asking the already answered question, I am a newbie to C and don't understand the solutions.Here is my function
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;
}
它引发错误
在线
怎么了?我只是将一个数组元素的值设置为另一个数组元素.
What's wrong? I am just setting the value of an array element to another array element.
所传递的arr被声明为
The arr passed is declared as
int S[4][4] = { { 1, 4, 10, 3 }, { 0, 6, 3, 8 }, { 7, 10 ,8, 5 }, { 9, 5, 11, 2} };
推荐答案
C使您可以在数组和指针上使用下标运算符[]
.在指针上使用此运算符时,结果类型是指针指向的类型.例如,如果将[]
应用于int*
,则结果将是int
.
C lets you use the subscript operator []
on arrays and on pointers. When you use this operator on a pointer, the resultant type is the type to which the pointer points to. For example, if you apply []
to int*
, the result would be an int
.
这正是正在发生的事情:您正在传递int*
,它对应于整数向量.一次在其上使用下标会使其变为int
,因此您无法在其上应用第二个下标.
That is precisely what's going on: you are passing int*
, which corresponds to a vector of integers. Using subscript on it once makes it int
, so you cannot apply the second subscript to it.
从您的代码看来,arr
应该是一个二维数组.如果将其实现为锯齿状"数组(即指针数组),则参数类型应为int **
.
It appears from your code that arr
should be a 2-D array. If it is implemented as a "jagged" array (i.e. an array of pointers) then the parameter type should be int **
.
此外,您似乎正在尝试返回本地数组.为了合法地执行此操作,您需要动态分配数组,并返回一个指针.但是,更好的方法是为4x4矩阵声明一个特殊的struct
,并使用它包装固定大小的数组,如下所示:
Moreover, it appears that you are trying to return a local array. In order to do that legally, you need to allocate the array dynamically, and return a pointer. However, a better approach would be declaring a special struct
for your 4x4 matrix, and using it to wrap your fixed-size array, like this:
// 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;
}
此打印以下内容:
3 8 5 2
10 3 8 11
4 6 10 5
1 0 7 9
这篇关于分配数组元素值时,C下标值既不是数组,也不是指针,也不是矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!