gpt4 book ai didi

c - 如何使用 memset 设置填充数组

转载 作者:太空宇宙 更新时间:2023-11-04 00:43:31 25 4
gpt4 key购买 nike

我有一个包含 GameBoard 的 Player 结构,它是一个二维字符数组。

当我使用 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);
}

我希望结果用'~'填充,但它要么破坏整个终端要么打印空白

最佳答案

这里:

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

关于c - 如何使用 memset 设置填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55399427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com