简体   繁体   中英

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 . 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. 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:

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.

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. 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.

So as @Mr.TAMER mentioned in his answer, you should use the following

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

OTOH, you can use the following rotate code for your reference! It rotates a 2d array to 90 degrees!

#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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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