如何在C中声明指向结构数组的指针 [英] How to declare pointer to array of structs in C
问题描述
指针和C的新手,我的程序需要结构数组的指针,并且能够将此指针传递给函数.
New to pointers and C and need for my program a pointer for an array of structs and be able to pass this pointer to a function.
声明结构数组类型的指针的正确方法是什么?可以使用该指针的函数参数应该是什么?
What is the correct way to declare a pointer of struct array type and what should be my function parameter that can take such pointer?
这是我的尝试:
#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]) {
...
}
这是我得到的警告:
warning: incompatible pointer types passing 'struct Card (*)[5]' to parameter of type 'struct Card **' [-Wincompatible-pointer-types]
我知道指针是不同的类型,但是我似乎无法弄清楚如何正确设置它.
I understand the pointers are different types but I cant seem to figure out how to set it correctly.
如果有人可以向正确的方向指出我,我将不胜感激.
I'll appreciate if someone can *pointer me in the right direction.
推荐答案
也许您想要做的是:
void printHandResults(struct Card (*hand)[]);
和这个:
void printHandResults(struct Card (*hand)[]) {
}
您正在做的是在主BUT中传递指向结构变量数组的指针,该函数设置为接收指向结构变量的指针数组而不是指针到一个结构变量数组!现在不会发生类型不匹配的情况,因此也就不会发出警告.
What you were doing was passing a pointer to an array of struct variables in the main, BUT, the function was set to receive an array of pointers to struct variables and not a pointer to an array of struct variables! Now the type mismatch would not occur and thus, no warning.
请注意,[]
,(方括号)的优先级高于(一元)解引用运算符*
,因此我们需要使用一组括号()
并将数组名称和*
括起来,以确保我们在这里谈论什么!
Note that []
, the (square) brackets have higher precedence than the (unary) dereferencing operator *
, so we would need a set of parentheses ()
enclosing the array name and *
operator to ensure what we are talking about here!
这篇关于如何在C中声明指向结构数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!