0

Im trying to get userInput from one function than use it in another. When I test to see if the char is working in the DetermineWhatCommand function the first time I type characters I get the wrong output but after that the next entered string appears correctly.

#include<stdio.h>
#include<string.h>
#define MAX 100




char * GetUserInput(){
  char userInput[MAX];
  fgets(userInput, sizeof (userInput), stdin);
  userInput[strcspn(userInput, "\n")] = '\0';

   return userInput;
}

void DetermineWhatCommand(char *userInput){
  printf(userInput);

}


int main() {

    char * userInput;
    userInput = new char[MAX];
    char exitTest[] = "exit";

    while(strcmp(exitTest, userInput) != 0){
        userInput = GetUserInput();
        DetermineWhatCommand(userInput);

   }
   return 0;
}

Output:

Hello    //First string entered
@        //What the output in the function looks like
Hello    //Second string entered
Hello    //What the output in the function looks like 
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
Matthew
  • 5
  • 5

2 Answers2

3

This

   char userInput[MAX];

Is on the stack - so goes out of scope when the function returns.

Either, pass it in as a parameter or use malloc to bung it on the heap.

BTW: new is C++ - If using C++ tag the question as so and use std::string

Also printf(userInput); is invariably wrong

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

When you use memory dynamically then it belong to the entire program rather than the scope where it has been defined.

In the OP's code the memory is free once control goes out of the scope of the function in which memory is being allocated "statically" i.e. scope of function GetUserInput.

Since this question has been tagged with label C despite new being used in it, I would be presenting your C version:

  char * GetUserInput()
  {
       char *userInput = malloc(MAX);
       //YOUR FUNCTIONALITY..........

       return userInput;
  } 
Gaurav
  • 1,570
  • 5
  • 17