Search code examples
cscanfstdio

scanf only reads first field


I want to read in two strings with scanf and store them in two variables. How ever only the first one seems to be read properly, the second one just returns (null), but I'm not sure why though.

int main(int argc, char **argv) {
  char *c, *p;

  printf("Enter a command with a parameter: ");
  scanf("%s%s", c, p);
  ...
}

Somebody got an idea, what's going wrong? I don't find any errors and for my understanding it should work.


Solution

  • char *c, *p;
    

    These are just pointers without any memory behind them. Moreover, they are uninitialized, so reading or assigning they value or reading from or assigning to the memory they point to would be undefined behavior and will spawn nasal demons.

    In order to read input from user, you need a place to save the memory to.

    char c[20], p[20];
    

    Will allocate 20 characters for c and 20 character for p. c and p are not pointers, but arrays char[20]. However arrays handlers "decay" (read: magically change) into pointers in most contexts.

    scanf for "%s" scanf modifier expects a pointer to char char* with enough memory to hold the inputted string.

    I would do:

    int main(int argc, char **argv) {
      char c[20], p[20];
    
      printf("Enter a command with a parameter: ");
      scanf("%19s%19s", c, p);
    }
    

    The 19 in the %19s limits scanf so that it does not reads input into memory region that is out of bounds in c and/or p pointers, which will lead to undefined behaviour too.