[英]return a pointer struct from a function
我试图返回要切换的行和列的用户输入(应该是一个名为Teaser的游戏),但是我不确定如何返回想要的值。
我得到的警告是:
warning: incompatible pointer to integer conversion returning 'move *' from a function with result type 'int' [-Wint-conversion]
typedef struct {
int row;
int column;
} move;
/* Function: getNextMove
* Description: Ask the user for a new move or if the user want to quit
* the game.
* Input: A pointer to a move structure. Coordinates for the next move
* or a signal from the user to end the game.
* Output: Return 0 if the user want to end the game, 1 otherwise.
* Return the coordinates for the next game through the
* structure pointed to.
*/
int getNextMove(move *nextMove) {
printf("Make a move (Row = 0 ends the game)\n");
printf("Row = ");
scanf("%d", &nextMove->row);
if (nextMove->row == 0)
{
return 0;
}
printf("Column = ");
scanf("%d", &nextMove->column);
return nextMove;
}
您犯了一个简单的错误。 该函数的文档说:
Output: Return 0 if the user want to end the game, 1 otherwise.
但是,相反,您将返回0
或nextMove
的值。
nextMove
是move*
,而不是int
,因此是警告。 这也是警告如此有用的原因,因为警告指出了您在返回错误内容时所犯的错误。
将return nextMove
更改为return 1
。
如函数标题注释所建议的,您不应返回多个值。 返回0或1以指示游戏状态,并通过scanf()函数调用更改nextMove指向的地址中存储的值:
int getNextMove(move *nextMove) {
printf("Make a move (Row = 0 ends the game)\n");
printf("Row = ");
scanf("%d", &nextMove->row);
if (nextMove->row == 0)
{
return 0;
}
printf("Column = ");
scanf("%d", &nextMove->column);
return 1;
}
对于记录,如果您确实想返回一个指向move结构的指针,则示例可能是:
move * getMove(void)
{
static move moveToReturn;
/* some operations on the move stucture */
return &moveToReturn
}
您(有时)返回参数。 有什么意义呢? 在这种情况下,无需返回任何内容。
但是,如果您确实想返回一个指向move
的指针,则您的函数应将其声明为其返回类型:
move * getNextMove(move * nextMove) {
...
return nextMove;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.