提前道歉,因為我對 C 和一般的指標非常陌生。我試圖將在我的主子程式中宣告的變數傳遞給另一個子程式,以便讓用戶輸入資訊更新主子程式中的變數值。但是我一定是錯誤地使用了指標,因為我已經嘗試了所有我能想到的但是我的主子中的變數沒有更新。
// --------------------------------------------------------------------------------
// Prototypes
// --------------------------------------------------------------------------------
void GetUserInfo(char* pstrState)
// --------------------------------------------------------------------------------
// Name: main
// Abstract: This is where the program starts.
// --------------------------------------------------------------------------------
void main()
{
//Variables
char strState;
//Getting User Info
GetUserInfo(&strState);
printf("STATE: %s", strState);
}
// --------------------------------------------------------------------------------
// Name: GetUserInfo
// Abstract: Prompts the user for info and validates the entries
// --------------------------------------------------------------------------------
void GetUserInfo(char* pstrState))
{
//Variables
int intChoice = 0;
//Getting State by numeric selection - this loop will continue until a selection is made
printf("STATE:\n");
while (intChoice != 1 && intChoice != 2)
{
printf("Please enter a '1' for OHIO or '2' for KENTUCKY.\n");
scanf("%d", &intChoice);
}
//Assigning state to variable
if (intChoice == 1)
{
//Building string and terminating
pstrState = malloc(5);
pstrState[0] = 'O';
pstrState[1] = 'H';
pstrState[2] = 'I';
pstrState[3] = 'O';
pstrState[4] = 0;
}
else if (intChoice == 2)
{
//Building string and terminating.
pstrState = malloc(9);
pstrState[0] = 'K';
pstrState[1] = 'E';
pstrState[2] = 'N';
pstrState[3] = 'T';
pstrState[4] = 'U';
pstrState[5] = 'C';
pstrState[6] = 'K';
pstrState[7] = 'Y';
pstrState[8] = 0;
}
uj5u.com熱心網友回復:
char strState;宣告單個char. 你想要char* strState;(指向字符的指標)。
更改GetUserInfo(char* pstrState);為GetUserInfo(char** pstrState);。pstrState現在是一個指向指標的指標!
在里面,GetUserInfo(char** pstrState);您需要更改pstrState為*pstrState.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379871.html
下一篇:使用C在搜索二叉樹中查找最長路徑
