0

I'm Trying to take names from the user in loop the user will enter how many names will be entered but the problem is when I use gets func in a loop every time it passes the very first gets in the loop lets say the user will enter 5 names because of this bug it can enter 4 names but enter the 1.name will shown on the screen too actually its not passing its taking it a space like ı didnt even entered first one its act like I just pressed enter and left it empty. here is the code;

for (int k = 0; k < namecounter; k++) {
    printf("\nEnter the %d.Name :", k + 1);
    gets(name_entry);
    names[k] = (char*)malloc(strlen(name_entry) + 1);
    if (names[k] == NULL) {
        printf("insufficient memory!..\n");
        exit(EXIT_FAILURE);
    }
    strcpy(names[k], name_entry);
}
  • 1
    [gets is bad](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) - please read – Ed Heal May 06 '20 at 20:15
  • 1
    Did you use `scanf` to read the value of `namecounter`? If so, it left a newline in the input buffer that `gets` is picking up. Try to avoid mixing `scanf` and `gets`/`fgets`. – dbush May 06 '20 at 20:22
  • 1
    [cast malloc is bad](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) - some more reading – Ed Heal May 06 '20 at 20:28

0 Answers0