简体   繁体   中英

return a pointer struct from a function

I'm trying to return the user input of which row and column to 'switch' (it's supposed to be a game called Teaser), but I'm not sure how to return the value that I want to.

The warning I'm getting is:

 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;
}

You made a simple error. The function's documentation says:

Output:      Return 0 if the user want to end the game, 1 otherwise.

But, instead, you're returning 0 or the value of nextMove .

nextMove is a move* , not an int , hence the warning. This is also why warnings are so helpful, because they have pointed out this mistake that you have made in returning the wrong thing.

Change return nextMove to return 1 .

You shouldn't return more than one value as suggested by the function banner comment. Return the 0 or 1 to indicate game status and the value stored in the address pointed to by nextMove is changed by the scanf() function calls:

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;
}

For the record if you did want to return a pointer to a move struct an example could be:

move * getMove(void)
{
    static move moveToReturn;

    /* some operations on the move stucture */

    return &moveToReturn
}

You are (sometimes) returning the argument. What's the point of that? There's no need to return anything in that case.

If you did want to return a pointer to a move , though, then your function should declare that as its return type:

move * getNextMove(move * nextMove) {
    ...
    return nextMove;
}

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