简体   繁体   English

struct array函数参数

[英]struct array function argument

I have the following code of declarations: 我有以下代码声明:

struct coord {
int x;
int y;
}
void rotateFig(struct coord[10][10]);

I need to implement rotateFig . 我需要实现rotateFig I tried to start with following: 我试着从以下开始:

void rotateFig(struct coord[10][10] c)
{
   //code
}

I can`t compile it - probaly the way I transfer c in the function definition is incorrect .How should I transfer c using given signature. 我不能编译它 - 可能我在函数定义中传递c的方式是不正确的。如何使用给定签名传输c。 Thank you 谢谢

Use this definition: 使用此定义:

void rotateFig(struct coord c[10][10])
{
   //code
}

The array is the actual parameter, so the dimensions have to come after its name, not before. 数组是实际参数,因此维度必须在其名称之后,而不是之前。

Though other answers ARE enough, I prefer passing it as a pointer and passing the dimensions with it, this is more dynamic, and is the same for the //code part: 虽然其他答案足够了,但我更喜欢将它作为指针传递并用它传递维度,这更加动态,对于//code部分也是如此:

void rotateFig(struct coord**, int, int);

void rotateFig(struct coord** c, int d1, int d2)
{
   //code
}

struct coord is a type and c is a variable of type struct coord which can hold 10 X 10 struct coord elements. struct coord是一种类型和c是类型的变量struct coord可容纳10 X 10 struct coord元素。

So it should be as follows 所以它应该如下

void rotateFig(struct coord c[10][10])

One thing to note when working with multi-dimension array in C is that it cannot be return back from a function. C多维数组时要注意的一点是它无法从函数返回。 For details, read this . 有关详情,请阅读此内容 So its not advised to use the above format as C by default passes arguments by value and not by address. 所以不建议使用上面的格式,因为默认情况下, C按值而不是按地址传递参数。

So as @Mr.TAMER mentioned in his answer, you should use the following 因此,@ Mr.TAMER在他的回答中提到,你应该使用以下内容

void rotateFig(struct coord** c, int d1, int d2)

OTOH, you can use the following rotate code for your reference! OTOH,您可以使用以下旋转代码供您参考! It rotates a 2d array to 90 degrees! 它将2d阵列旋转到90度!

#include <stdio.h>

#define N 10 
int matrix[N][N];

void display()
{
    int i, j;

    printf("\n");
    for (i=0; i<N; i++) {
        for (j=0; j<N; j++) 
            printf("%3d", matrix[i][j]);
        printf("\n");
    }
    printf("\n");

    return;
}

int main()
{
    int i, j, val = 1;
    int layer, first, last, offset, top;

    for (i=0; i<N; i++)
        for (j=0; j<N; j++)
            matrix[i][j] = val++;

    display();

    for (layer = 0; layer < N/2 ; layer++) {
        first = layer;
        last = N - layer - 1;
        for (i=first; i< last ; i++) {
            offset = i - first;
            top = matrix[first][i];

            matrix[first][i] = matrix[last-offset][first];
            matrix[last-offset][first] = matrix[last][last-offset];
            matrix[last][last-offset] = matrix[i][last];
            matrix[i][last] = top;
        }
    }

    display();
    return 0;
}

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM