這個問題在這里已經有了答案: 指標未在 main 中更新 1 個答案 可以在其范圍之外訪問區域變數的記憶體嗎? (21 個回答) 23 分鐘前關閉。
我正在用 c 開發一個井字棋棋盤游戲以用于學習目的,并且我正在將 a 傳遞char**給一個函式,該函式為給定引數分配一個存盤玩家姓名的指標陣列。
在變數賦值時,我可以在函式呼叫中列印初始化變數的結果,void initPlayerNames(char** playerNames)但是當我回傳呼叫函式時,程式不會列印結果。
我的理解是指標變數存盤另一個資料結構的地址,因此我希望在函式呼叫中修改指標變數后列印指標變數的結果。
請幫助我了解我在哪里犯了錯誤
void initPlayerNames(char** playerNames) {
const int playerNameLength = 100;
cout << "Player one, enter your name: ";
char p1[playerNameLength];
cin.getline(p1, playerNameLength);
cout << "Player two, enter your name: ";
char p2[playerNameLength];
cin.getline(p2, playerNameLength);
char* names[2] = {p1, p2};
playerNames = names;
cout << "Player 1 = " << playerNames[0] << endl;
cout << "Player 2 = " << playerNames[1] << endl;
};
void game() {
char** playerNames = nullptr;
cout << "Welcome! \n";
initPlayerNames(playerNames);
cout << "Player 1 = " << playerNames[0] << endl;
cout << "Player 2 = " << playerNames[1] << endl;
};
輸出
玩家一,輸入你的名字:Kevin Patel
玩家二,輸入你的名字:史蒂夫喬布斯
球員 1 = 凱文·帕特爾
玩家 2 = 史蒂夫·喬布斯
uj5u.com熱心網友回復:
指標playerNames設定如下:
char* names[2] = {p1, p2};
playerNames = names;
但是,當函式initPlayerNames()退出時names,p1和p2都被銷毀,因此playerNames指向未分配的記憶體。
此外,playerNames它本身initPlayerNames()是一個在函式退出時被銷毀的變數(就像在函式中一樣void func(int a),更改為a不會反映在呼叫者函式中)。
要解決這個問題:
將涉及的變數宣告為
static這意味著它們也將在函式未運行時分配。但是請注意,這主要是為了說明生命周期問題,此解決方案并非沒有問題(在多執行緒應用程式中不安全,并且在其函式之外公開看似區域變數 - 就像使用全域變數一樣)。傳遞指向 的指標或參考
playerNames。作為老式的,我更喜歡指標,因此可以更清楚地更改傳遞的引數:
void initPlayerNames(char*** playerNames) {
const int playerNameLength = 100;
cout << "Player one, enter your name: ";
static char p1[playerNameLength];
cin.getline(p1, playerNameLength);
cout << "Player two, enter your name: ";
static char p2[playerNameLength];
cin.getline(p2, playerNameLength);
static char* names[2] = {p1, p2};
*playerNames = names;
cout << "Player 1 = " << (*playerNames)[0] << endl;
cout << "Player 2 = " << (*playerNames)[1] << endl;
};
并像這樣呼叫函式:
initPlayerNames(&playerNames);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/421201.html
標籤:
上一篇:AndroidKotlinPDFtron:如何將pdf從內部存盤附加到電子郵件。為什么我的錯誤“無法附加檔案”。發生了什么?
