gpt4 book ai didi

c - 尝试从c中的文件中的单词(文本)中进行动态内存分配

转载 作者:行者123 更新时间:2023-11-30 17:01:30 24 4
gpt4 key购买 nike

我试图使用动态内存分配来找出文件中文本的不同单词的数量。但是,我没有得到正确的结果。文本可以包含标点符号。程序如下:

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

int different_words(FILE *fp);

int main(int argc, char *argv[]) {

FILE *fp;

different_words(fp);
return 0;
}

int different_words(FILE *fp) {

int i,j,ic=0,sum=0,sum2=0;
char d[100];
char **A;

fp=fopen("file.txt","rt");
if ((fp = fopen("file.txt", "rt"))== NULL) { //opening the file
printf("cannot read file\n");
exit(1);
}
while (fscanf(fp,"%s",&d)!=EOF)
sum++;
A=(char**)malloc(sum*sizeof(char*)); //allocate memory for all the words
if (A==NULL) {
fclose(fp);
return 0;
}
rewind(fp);
while(fscanf(fp,"%s",&d)!=EOF){
if (strchr("!?.,:",d[strlen(d)-1])==0) //edit
A[ic]=(char*)malloc(strlen(d)+1);
else
A[ic]=(char*)malloc(strlen(d));
if (A[ic]==NULL) {
fclose(fp);
return 0;
}
if (strchr("!?.,:",d[strlen(d)-1])!=0)
for (j=0;j<=strlen(d)-2;j++)
A[ic][j]=d[j];
else
strcpy(A[ic],d);
if (++ic==sum)
break;
}
for (i=0;i<sum;i++){
for (j=0;j<i;j++){
if (strcmp(A[i],A[j])==0)
break;
}
if (i==j) {
sum2++; //finding the number of different words in the text
}
}
printf ("Number of different words in the text: %d\n",sum2);
return sum2;
}


----------

最佳答案

问题出在这里:

if (A=NULL) {
fclose(fp);
return 0;
}

您将 A 分配给 NULL,而不是检查它是否为 NULL。将其更改为

if (A==NULL) {
fclose(fp);
return 0;
}

还有,共识是你shouldn't cast the return value of malloc你还应该看看this关于从文件中读取数据。

关于c - 尝试从c中的文件中的单词(文本)中进行动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37008330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com