c中的字计数器不工作
我有一个c代码,如下所示。c中的字计数器不工作,c,string,pointers,C,String,Pointers,我有一个c代码,如下所示。 我想计算用分隔符分隔的文本中的字数。 代码编译但停止。 有什么问题吗? 下面是我的代码 #include <stdio.h> #include <string.h> int WordCount(char *text,char delimiter) { char *s; int count = 0; strcpy(s,text); while(*s){ if(*s==delimiter){
我想计算用分隔符分隔的文本中的字数。
代码编译但停止。
有什么问题吗?
下面是我的代码
#include <stdio.h>
#include <string.h>
int WordCount(char *text,char delimiter)
{
char *s;
int count = 0;
strcpy(s,text);
while(*s){
if(*s==delimiter){
count++;
}
}
return count;
}
int main(void)
{
char *line = "a,b,c,d,e";
printf("%d\n",WordCount(line,','));
return 0;
}
#包括
#包括
int字数(字符*文本,字符分隔符)
{
char*s;
整数计数=0;
strcpy(s,文本);
而(*s){
如果(*s==分隔符){
计数++;
}
}
返回计数;
}
内部主(空)
{
char*line=“a,b,c,d,e”;
printf(“%d\n”,字数(行,,);
返回0;
}
s
是未初始化的指针,而不是数组对象
s
是一个未初始化的指针,而不是数组对象。您忘记了递增指针s
,因此您有一个无限循环,而不是复制字符串(需要为其分配内存),只需让它指向输入即可
int WordCount(char *text,char delimiter)
{
char *s = text;
int count = 0;
// strcpy(s,text);
while(*s){
if(*s==delimiter){
count++;
}
++s;
}
return count;
}
您忘记了递增指针
s
,因此您有一个无限循环,而不是复制字符串(需要为其分配内存),而是让它指向输入
int WordCount(char *text,char delimiter)
{
char *s = text;
int count = 0;
// strcpy(s,text);
while(*s){
if(*s==delimiter){
count++;
}
++s;
}
return count;
}
char*s代码>-为堆栈或堆中的s
分配内存
程序中的错误
- 声明时必须初始化所有变量
- 应为指针变量分配/分配有效内存
- 不确定循环,它总是检查字符串的第一个字符
如下所示修改代码
...
char *s = NULL;
int count = 0;
s = text;
while(*s);
{
if (*s == delimiter)
{
count++;
}
s++;
}
...
char*s代码>-为堆栈或堆中的s
分配内存
程序中的错误
- 声明时必须初始化所有变量
- 应为指针变量分配/分配有效内存
- 不确定循环,它总是检查字符串的第一个字符
如下所示修改代码
...
char *s = NULL;
int count = 0;
s = text;
while(*s);
{
if (*s == delimiter)
{
count++;
}
s++;
}
...
您也不会通过增加指针s来实际移动字符串。我很确定你的WordCount例程可能是一个无限循环的情况。你也没有增加指针s来实际移动字符串。我很确定你的WordCount例程可能是一个无限循环的情况。他不需要复制,所以为什么要分配?所以现在你总是用s++更新s,如果s[count]==delimeter,你本质上是在重复计算,因为你增加count,然后使用s[count]引用他不需要复制,那么为什么要分配呢?现在你总是用s++更新s,如果s[count]==delimeter,你实际上是在重复计数,因为你增加了count,然后使用s[count]引用