【发布时间】:2024-04-17 00:45:01
【问题描述】:
我试图将文件中的单词添加到二维数组中,问题是在第 7 个单词之后,单词开始变得奇怪,有谁知道这可能会导致这种情况吗?
void count_words(WordCount **wclist, FILE *infile)
{
int num_words = 0;
char ch;
int k=0;
char **pook;
int flagA=0;
pook = malloc(4096*sizeof(char*));//creates a 2d array for every word from the file
for(int i = 0 ; i <4096 ; i++)
{
pook[i] = malloc(50 * sizeof(char*));
}
while((ch=fgetc(infile))!=EOF)
{
ch=tolower(ch);
if(flagA==0)
{
if(isalpha(ch)!=0)
{
num_words++;
flagA=1;
strcat(pook[k]+0, &ch);
}
}
else
{
if(isalpha(ch)!=0)
{
strcat(pook[k]+0, &ch);
}
else
{
flagA = 0;
k++;
}
}
}
for(int i =0 ; i < num_words ;i++)
{
printf("%s\n",pook[i]);
add_word(wclist , pook[i]);
}
}
输入:
input is text file that contains :
ilona.txt
main.c
makefile
wc_sort.o
word_count.c
word_count.h
words
这是输出的样子: 伊洛纳 文本文件 主要的 C 生成文件 厕所 种类 ○ 单词 数数 C 单词 数数 H 单词
这才是真正的输出:
the output is :
ilona
txt
main
c
makefile
wc
sort
o
w o r d
c
o
u
n
t
c
w
o
r
d
t
h
words
*/
【问题讨论】:
-
不是bug,但
pook[i] = malloc(50 * sizeof(char*));不应该是pook[i] = malloc(50 * sizeof(char));(为49个字符串加上空终止符分配空间)? -
fgetc的返回值应存储在int变量中,因为EOF可能无法由char变量表示。因此ch应该是int。 -
仅基于您的函数名称,我看不出需要任何动态分配whatsoever。仅仅因为你可以并不意味着你应该。
read_words似乎更适合您似乎想要做的事情。 -
另外关于
strcat,第一个参数指向一个分配的内存块,它最初具有不确定的内容。如果稍后将其传递给strcat,则需要在分配后将第一个字节初始化为0。
标签: c loops multidimensional-array malloc strcat