如何使用memset设置填充数组

时间:2019-03-28 13:58:05

标签: c

我有一个Player结构,其中包含GameBoard,它是2个字符数组。

当我使用memset时,它不会设置数组

我尝试使用板的地址(&,*),但没有这些符号

如果我在'initializeBoard'中使用指向Player变量的指针,则可以使它工作,但是赋值操作表明不要使用指针

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

const int ROWS = 10;
const int COLS = 10;

const char *PLAYERONE = "Player 1";
const char *PLAYERTWO = "Player 2";
const char WATER = '~';
const int NUM_SHIPS = 5;

typedef struct gameBoard {
    char board[ROWS][COLS];
} GameBoard;

typedef struct human {
    char name[20];
    GameBoard gameBoard;
} Player;

// function prototypes

void displayGameBoard(Player player);
void initializeBoard(Player player);
void initializePlayer(Player *player, const char *name);






// main function
int main() {
    Player playerOne;
    Player playerTwo;
    // call function welcomeScreen

    initializePlayer(&playerOne, PLAYERONE);
    // end program
    return 0;
}

void displayGameBoard(Player player) {
    int row;
    int col;
    printf("%s's Game Board\n", player.name);
    printf("---------------------------------------------\n");
    printf("|   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |\n");
    printf("---------------------------------------------\n");
    for (row = 0; row < ROWS; row++) {
        printf("| %d |", row);
        for (col = 0; col < COLS; col++) {
            printf(" %c |", player.gameBoard.board[row][col]);
        }
        printf("\n");
    }
    printf("---------------------------------------------");
}

void initializeBoard(Player player) {
    memset(*player.gameBoard.board, WATER, sizeof(player.gameBoard.board));
}

void initializePlayer(Player *player, const char *name) {
    char playerName[20];
    GameBoard playerBoard;
    strcpy(player->name, playerName);
    player->gameBoard = playerBoard;
    initializeBoard(*player);
    displayGameBoard(*player);
}

我希望结果用'〜'填充,但是它会破坏整个终端或打印空白

2 个答案:

答案 0 :(得分:3)

问题是,您在此处通过值传递了玩家结构

initializeBoard(*player);

因此,您实际上是在制作副本。传递一个指针并像这样处理原始结构:

initializeBoard(player);

,然后将initializeBoard函数更改为:

void initializeBoard(Player *player) {
   memset(player->gameBoard.board, WATER, sizeof(player->gameBoard.board)); 
}

然后它将按预期工作。您也应该更改displayBoard()函数,因为没有理由传递值,而且计算量更大(复制整个结构)

答案 1 :(得分:3)

这里:

void initializeBoard(Player player) {
    memset(*player.gameBoard.board, WATER, sizeof(player.gameBoard.board));
}

您正在通过复制而不是引用传递Player对象。您要设置的对象不是您要设置的对象,并且无论如何都是临时的。在堆栈上传递大型结构也效率不高(在这种情况下,您可能还需要重新考虑displayGameBoard()的签名)。另外,成员board不需要取消引用。

void initializeBoard(Player* player);

...

void initializeBoard(Player* player) 
{
    memset( player->gameBoard.board, WATER, sizeof(player->gameBoard.board));
}

然后在initializePlayer()中调用它:

initializeBoard(player);