一个函数产生一个无限循环

时间:2017-06-07 15:11:52

标签: c

我编写了以下函数,当我运行它时,它产生一个无限循环,我不明白为什么。

此函数创建动态字符串的动态数组。每个这样的字符串都以给出的字母开头,或者以与给出的字母兼容的大写字母开头:

void wordsStartWithLetter(char letter, char *str,char***newstr,int *numOfWords) 
{
    int i=0, count=0;
    char *word;
    char *delimiter = " ";

    while (str[i] != '\0')
    {
        if (str[i]==letter ||str[i]==(letter-32 )) //if it founds the letter at the begining of the word, than run till the space//
        {
            while (str[i] != ' ' && str[i] != '\0' ) 
              i++;      //counting the number of words beginng with the letter given//
            count++;        
        }
        else
        {
            while (str[i] != ' ' && str[i] != '\0' ) 
                i++;
        }
    }

    *newstr = (char**)malloc (sizeof(char*)*count); 
    *numOfWords=count;
    i=0;

    word = strtok(str, delimiter);      //we use strtok to separate each word from the origin string//

    while(word!=NULL)            
    {
        if (word[0]==letter ||word[0]==letter-32)
        {
            (*newstr)[i]=word;                 //insert the compatible words into the new 2D-string//
            i++;
        }
        word = strtok(NULL, delimiter);
    }

}

我通过以下方式调用该函数:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

#define SIZE 50

void Ex();
void wordsStartWithLetter(char letter, char *str,char***newstr,int *numOfWords) ;

void main()
{

    Ex();
}

void Ex()
{
    char ch;
    char str[SIZE];
    char **newstr;
    int numOfWords,i;

    printf("please enter a string: ");
    _flushall();
    gets(str);
    printf("plese enter a letter: " );
    _flushall();
    ch=_getche();
    wordsStartWithLetter(ch, str,&newstr,&numOfWords);

    ("the words of the origin string which start which %c :\n",ch);
    for(i=0;i<numOfWords;i++)
        printf("%s\n",newstr[i]);

    for (i=0;i<numOfWords; i++)
       free(newstr[i]);
    free(newstr);
}

1 个答案:

答案 0 :(得分:1)

考虑此输入字符串"a b"并假设该字母为c

i0时,您输入以下代码,因为str[0]a且与该字母不匹配:

    else
    {
        while (str[i] != ' ' && str[i] != '\0' ) 
            i++;   // Increment i from 0 to 1
    }

在上面的块中,您将i增加到1,然后离开该块,因为str[1]' '

在下一个主循环中,您将再次点击此代码块:

    else
    {
        while (str[i] != ' ' && str[i] != '\0' ) 
            i++;   // No increment, i.e. i stays at 1
    }

但你会增加i(因为str[1]是一个空格)。换句话说 - i保留在1,你有一个无限循环。

也许你可以解决这个问题:

    else
    {
        while (str[i] != ' ' && str[i] != '\0' ) 
            i++;   // No increment, i.e. i stays at 1

        // Add this line to remove the spaces
        while (str[i] == ' ') i++;
    }