[英]Changing pointer to a struct, passed by reference
我對一個名為“PlayBoard.c”的文件進行了調用:
MoveSucc = putBoardSquare(theBoard, getX, getY, nextTurn);
其中 'theBoard' 是指向 struct Board 的指針。 在 function 內部,我通過引用指向另一個更大的板結構的指針來更改板的大小。 它會改變調用 MoveSucc 的“PlayBoard.c”上的“theBoard”嗎?
編輯: putBoardSquare 在另一個源文件中定義
編輯:我添加了相關功能
Boolean putBoardSquare(BoardP theBoard, int X, int Y, char val)
{
if (val != 'X' && val != 'O')
{
reportError(BAD_VAL);
return FALSE;
}
if (X<0 || Y<0)
{
reportError(OUT_OF_BOUND);
return FALSE;
}
if (X>theBoard->height || Y>theBoard->width)
{
theBoard = expandBoard(theBoard, X,Y);
}
printf("BOARD SIZE IS %d*%d\n",theBoard->height,theBoard->width);
if (theBoard->board[X][Y] == 'X' || theBoard->board[X][Y] == 'Y' )
{
reportError(SQUARE_FULL);
return FALSE;
}
if (val != turn)
{
reportError(WRONG_TURN);
return FALSE;
}
theBoard->board[X][Y] = val;
printf("PUT %c\n",theBoard->board[X][Y]);
changeTurn(val);
return TRUE;
}
static BoardP expandBoard(ConstBoardP theBoard, int X, int Y)
{
int newWidth = theBoard->width;
int newHeight = theBoard->height;
if (X>theBoard->height)
{
newHeight = (newHeight+1) * 2;
}
if (Y>theBoard->width)
{
newWidth = (newWidth+1) * 2;
}
BoardP newBoard = createNewBoard(newWidth,newHeight);
copyBoard(theBoard,newBoard);
printf("RETUNRNING NEW BOARD OF SIZE %d*%d\n",newHeight,newWidth);
return newBoard;
}
如您所見,當用戶嘗試將“X”或“O”放置在板外時,需要對其進行擴展(我知道因為我已經在 expandBoard() 和 putBoardSquare() 中打印了新板的尺寸) . 但是'PlayBoard.c'中的指針似乎並沒有改變......
我的問題:如何更改作為參數傳遞給另一個 function 的結構的指針? 在“PlayBoard.c”中,我將一個結構作為參數傳遞,我希望 putBoardSquare 將其引用到另一個結構,這也將在 PlayBoard.c 中生效。
我清楚了嗎?
編輯
theBoard = expandBoard(theBoard, X,Y);
此賦值僅更改局部變量。 您必須添加一級間接,如下所示:
MoveSucc = putBoardSquare(&theBoard, getX, getY, nextTurn);
Boolean putBoardSquare(BoardP *theBoard, int X, int Y, char val)
{
/* ... */
*theBoard = expandBoard(theBoard, X,Y);
/* ... */
}
您的問題令人困惑(也許您應該發布您擁有的代碼),但是您遇到的錯誤僅僅是由於PlayBoard.c
中不可用的結構定義造成的。 例如,如果你只有
struct foo;
void foo(struct foo *foov) { ... }
沒有可用的 foo 定義,如
struct foo { int a; ... }
那么您將無法訪問結構的成員(請參閱“不透明類型”)。
如果我理解正確並且您想更改theBoard
指向的位置,則需要將其定義為指向指針的指針,而不是指針。
MoveSucc = putBoardSquare(&theBoard, getX, getY, nextTurn);
並將putBoardSquare()
中的參數更改為**
並在設置指針時執行此操作(假設x
是指針):
*theBoard = x;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.