while-loop + fgets错误

时间:2014-10-21 02:24:04

标签: c

#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;   
}

当我运行此代码时,程序停止工作。我是c的新手,可能会犯一些错误。我认为问题是while循环或fgets()函数。

编辑:我纠正了while循环但是我不理解如何初始化数组。随着循环的进行,数组中的每个元素都不会被填充吗?

2 个答案:

答案 0 :(得分:4)

您将'count'初始化为0,点击while循环并使用'count - 1'作为数组索引。数组索引-1肯定会导致程序崩溃。

答案 1 :(得分:0)

您的代码中至少有两个undefined behavior个案例:

  1. 你没有初始化任何数组,这意味着它们中的指针是不确定的。
  2. 您在第一次迭代中使用负索引。
  3. 此外,您不应忘记fgets将换行符保留在字符串中,因此您的字符串比较将永远不会成功。


    我推荐的解决方案:count小于100时的循环,然后在循环内使用"done"检查"done\n"(或更确切地说是ans) (在复制之前)然后突破循环。