我目前正在用 C 語言開發井字游戲,但遇到了一些障礙。我已經定義了一個結構來表示游戲板(見下文,“board.h”),并試圖定義一種“建構式”函式,它將動態初始化板結構的默認版本并回傳一個指向它的指標。更具體地說,我很難確定應該如何使用 malloc 函式為prowsBoard 結構的欄位動態分配空間,包括 malloc 函式的輸入以及如何從型別轉換 malloc 函式的結果“void pointer” - void *- 鍵入“指向 int 指標陣列的指標”。
在下面的代碼框中,我包含了我的“board.h”和“board.c”檔案的內容: board.h 包含我對 Board 結構的定義以及在 board.c 中實作的函式的原型。在 board.c 中,我已經嘗試實作initBoard在堆上初始化 Board 結構并回傳指向它的指標的函式,但是我不確定我對prows欄位初始化的處理是否正確(我已經包含了我的步驟在initBoard功能實作中逐步推理)。我希望有人可以幫助我了解如何使用 malloc 來初始化prows欄位以及為什么必須這樣做。
/***
* =======================================
* board.h
* =======================================
***/
#ifndef BOARD_H_INCLUDED
#define BOARD_H_INCLUDED
const unsigned int boardDim = 3;
typedef struct {
int * (*prows)[boardDim];
int score;
unsigned int turn;
_Bool isTerminal;
} Board;
Board * initBoard(void);
#endif
/***
* =======================================
* board.c
* =======================================
***/
#include <stdio.h>
#include <stdlib.h>
#include "board.h"
/*
* to initialize the prows field of a new Board struct, I figured it would be a good
* approach to first initialize the array of int pointers to which prows points to and
* then initialize prows by taking the address of the initialized array of int pointers
*/
Board * initBoard(void) {
/*
* initialize array of int pointers called "rows" ...
*
* from what I know, rows stores the address of the first element in the array's
* memory block, so a pointer to the "rows" array will essentially be a pointer to an
* int pointer, so we should cast the returned void pointer (void *) from malloc to
* type pointer to int pointer (int **) ...
*
* lastly, because rows will contain (boardDim) number of pointers (one for each row
* in the board), inside malloc, I should pass "boardDim * sizeof(int *)" to allocate
* (boardDim) number of int pointers
*/
int * rows[boardDim] = (int **) malloc(boardDim * sizeof(int *));
int * row;
for (row = rows; row < rows boardDim; row ) {
row = (int *) malloc(sizeof(int));
}
int * (*prows)[boardDim] = &rows;
int score = 0, turn = 0;
_Bool isTerminal = 0;
Board * board = (Board *) malloc(sizeof(Board));
board->prows = prows;
board->score = score;
board->turn = turn;
board->isTerminal = isTerminal;
return board;
}
uj5u.com熱心網友回復:
你的程式過于復雜——你應該花一些時間重新考慮你的方法并計劃好一切。
然而,這里是如何分配你想要的東西:
#define boardDim 3
int *(*prows)[boardDim];
prows = malloc(sizeof(int *[boardDim]));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/506500.html
上一篇:此代碼如何生成記憶體對齊切片?
