apologies ahead of time as I am VERY new to C and pointers in general. I'm attempting to pass a variable declared in my main sub to another sub in order to have the user input information that will then update the variable value in the main sub. However I must be using pointers incorrectly as I have tried all I can think of but the variables in my main sub are not updating.
// --------------------------------------------------------------------------------
// 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;
}
CodePudding user response:
char strState;
declares a single char
. You want char* strState;
(pointer to char).
Change GetUserInfo(char* pstrState);
to GetUserInfo(char** pstrState);
. pstrState
is now a pointer to a pointer!
Inside GetUserInfo(char** pstrState);
you need to change pstrState
to *pstrState
.