如何在C中声明指向结构数组的指针

use*_*867 7 c struct pointers

新的指针和C,我的程序需要一个结构数组的指针,并能够将此指针传递给函数.

声明struct数组类型指针的正确方法是什么?我的函数参数应该采用哪种指针?

这是我的尝试:

#define HAND_SIZE 5

struct Card {
    char suit;
    char face;
};

void printHandResults(struct Card *hand[HAND_SIZE]);

int main(void)
{
    struct Card hand[HAND_SIZE];
    struct Card (*handPtr)[HAND_SIZE]; //Correct way to declare?
    handPtr = &hand; 
    ...
    printHandResults(handPtr);

}
void printHandResults(struct Card *hand[HAND_SIZE]) {
...
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的警告:

warning: incompatible pointer types passing 'struct Card (*)[5]' to parameter of type 'struct Card **' [-Wincompatible-pointer-types]
Run Code Online (Sandbox Code Playgroud)

我理解指针是不同的类型,但我似乎无法弄清楚如何正确设置它.

如果有人能指出我正确的方向,我将不胜感激.

skr*_*ngr 6

也许你想要的是这样做:

void printHandResults(struct Card (*hand)[]);
Run Code Online (Sandbox Code Playgroud)

还有这个:

void printHandResults(struct Card (*hand)[]) {

}
Run Code Online (Sandbox Code Playgroud)

你正在做的是在main中传递一个指向struct变量数组的指针,但是,该函数被设置为接收一个指向struct变量的指针数组,而不是一个指向struct变量数组的指针!现在不会发生类型不匹配,因此没有警告.

请注意[],(方形)括号的优先级高于(一元)解除引用操作符*,因此我们需要一组括()起数组名称和*运算符的括号来确保我们在这里讨论的内容!


Rem*_*eau 5

数组降级为指向第一个数组元素的原始指针.所以你可以做更像这样的事情:

#define HAND_SIZE 5

struct Card {
    char suit;
    char face;
};

void printHandResults(struct Card *hand);

int main(void)
{
    struct Card hand[HAND_SIZE];
    ...
    printHandResults(hand);
}

void printHandResults(struct Card *hand)
{
    for (int i = 0; i < HAND_SIZE; ++i)
    {
        // print hand[i].suit and hand[i].face as needed...
    }
}
Run Code Online (Sandbox Code Playgroud)

或者:

#define HAND_SIZE 5

struct Card {
    char suit;
    char face;
};

void printHandResults(struct Card *hand, int numInHand);

int main(void)
{
    struct Card hand[HAND_SIZE];
    ...
    printHandResults(hand, HAND_SIZE);
}

void printHandResults(struct Card *hand, int numInHand)
{
    for (int i = 0; i < numInHand; ++i)
    {
        // print hand[i].suit and hand[i].face as needed...
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,为卡阵列创建一个新的typedef,然后您可以创建该类型的变量和指针:

#define HAND_SIZE 5

struct Card {
    char suit;
    char face;
};

typedef struct Card Hand[HAND_SIZE];

void printHandResults(Hand *hand);

int main(void)
{
    Hand hand;
    ...
    printHandResults(&hand);
}

void printHandResults(Hand *hand)
{
    for (int i = 0; i < HAND_SIZE; ++i)
    {
        // print hand[i].suit and hand[i].face as needed...
    }
}
Run Code Online (Sandbox Code Playgroud)