简体   繁体   中英

While-loop + fgets error

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdlib>
int main ()
{
    char ans[100];
    int count;
    count=0;
    char *arr[100];
    char *srtarr[100];

    while(count<100)
    {
        if(strcmp(ans,"done\n")!=0)  
        {      
            printf("Enter names when done type done:");
            fgets(ans,100,stdin);       
            arr[count]=strdup(ans);
        }
        printf("%s",arr[count]);
        count++;
     }

    system("pause");
    return 0;   
}

When I run this code the program stops working. Im very new to c and might have made a few errors. I think the problem is either the while loop or the fgets() function.

EDIT: I corrected the while loop however I'm not understanding how to initialize the array. Doesn't each element within the array get filled as the loop progresses?

You initialize 'count' to 0, hit the while loop and use 'count - 1' as an array index. An array index of -1 definitely could crash your program.

You have at least two cases of undefined behavior in your code:

  1. You don't in initialize any of the arrays, meaning the pointers in them are indeterminate.
  2. You use a negative index in the first iteration.

Also, you should not forget that fgets leave the newline in the string, so your string comparison will never succeed.


My recommended solution: A loop while count is less than 100 , then inside the loop check for "done" (or rather "done\\n" ) using ans (before duplicating it) and break out of the loop then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM