【发布时间】:2013-02-20 19:29:52
【问题描述】:
我正在尝试实现计算文本文件中字数的函数。
到目前为止,这是我的尝试。
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char word[1000];
int count = 0, i;
int *ptr = NULL;
printf("Enter filename: ");
scanf("%s", word);
fp = fopen(word, "r");
while(fscanf(fp, "%s", word) != EOF) //dynamically allocate contents of the file into word
ptr = (int *)malloc(sizeof(int));
for(i = 0; i < 4000; i++)
{
if(word[i] == ' ')
count++;
}
printf("Total: %d", count);
return 0;
}//main
当我使用 gcc- 编译时,我得到类似 "variable 'ptr' set but not used" 之类的错误,但我以为我在动态分配的内容时使用了它归档到word[80]。
我认为我的单词计数器存在严重问题......当显然有 200 多个单词时,它也会返回 0。有人可以请教我吗?
【问题讨论】:
-
while 循环和 malloc 损坏并泄漏内存。不要施放malloc。 word 是 1000 个字符,你的 for 循环循环 4000 次等等
-
那么你的单词计数器怎么样?完全没有反馈...