【发布时间】:2017-06-07 15:11:52
【问题描述】:
我写了以下函数,当我运行它时,它会产生一个无限循环,我不明白为什么。
此函数创建一个动态字符串的动态数组。每个这样的字符串都以给定的字母开头,或者以与给定字母兼容的大写字母开头:
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);
}
【问题讨论】:
-
函数怎么调用?请显示minimal reproducible example。
-
如果您的
while (str[i] != '\0')循环遇到' '它不再增加i,因此它将永远运行。 -
调试,在你的代码中打印 valors 以了解它在哪里循环。还要避免强制转换 malloc 的结果。
-
无关,但你不应该重复代码;只需将 while 循环移出 if/else:
if(... == letter ...) { ++count; } while(...){...}
标签: c