下面的代码正在生成编译器警告:从不兼容的指针类型返回。我要返回的类型似乎是问题所在,但我似乎无法解决此警告。
我尝试将手的类型更改为int *。也尝试过返回&hands。
int * dealDeck(int numPlayers, int numCards, int cardDeck[])
{
static int hands[MAX_PLAYERS][MAX_CARDS]={0};
int start = 0;
int end = numCards;
int player, hand, j;
int card;
for(player = 0; player < numPlayers; player++)
{
for(hand = start, j=0; hand < end; hand++,j++)
{
card = cardDeck[hand];
hands[player][j] = card;
}
start = end;
end += numCards;
}
return hands;
}
此函数应返回指向数组“手”的指针。然后将此数组传递给另一个函数,该函数将打印出其元素。
答案 0 :(得分:1)
hands
变量不是int *
,而是int **
因此,您需要返回一个int **
这是一个二维数组。
答案 1 :(得分:1)
首先,您已经声明了返回类型int *
,这意味着您想返回一个数组,而您想返回一个二维数组。正确的类型通常是int **
,但这不会在这里删减。您选择使用固定大小的静态数组。这意味着,您需要将指针返回到一些大小为MAX_CARDS * sizeof(int)的结构(以及正确的类型,这是这里的真正问题)。 AFAIK,无法在C *中指定该返回类型。
尽管有很多选择。如果仅指定1个大小(static int *hands[MAX_PLAYERS]
或static int **hands
),则可以保留静态方法,但是您需要动态分配内部数组。
理智的方法通常是“按引用调用”,即在调用函数之前通常定义数组,并将其作为参数传递给函数。然后,该函数直接修改外部变量。尽管这将对您的代码的可维护性产生巨大的帮助,但令我惊讶的是,它并没有摆脱警告。这意味着,最好的解决方案可能是在调用函数之前动态分配数组,然后将其作为参数传递给函数,以便它可以访问它。这也解决了以下问题:是否需要初始化数组,以及= {0}
是否是可读性强的方法(对于多维数组),因为您必须“手动”对其进行初始化。
示例:
#include <stdio.h>
#include <stdlib.h>
#define PLAYERS 10
#define DECKS 20
void foo(int **bar)
{
bar[0][0] = 777;
printf("%d", bar[0][0]);
/*
* no point in returning the array you were already given
* but for the purposes of curiosity you could change the type from
* void to int ** and "return bar;"
*/
}
int main()
{
int **arr;
arr = malloc(sizeof(int *) * PLAYERS);
for (size_t d = 0; d < DECKS; d++) {
/* calloc() here if you need the zero initialization */
arr[d] = malloc(sizeof(int) * DECKS);
}
foo(arr);
return 0;
}
*某些编译器会调用int (*)[20]
之类的类型,但这不是有效的C语法