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

标签 c memory dynamic malloc allocation

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

#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/

相关文章:

java - java内存池是怎么划分的?

java - 如何使用 perfmon 记录 tomcat 进程的 CPU 和内存使用情况

c# - 为动态对象创建 linq 表达式树

c - 我需要添加什么才能将输出显示给用户?

c - 从命令行获取参数并无法打开文件

c - 我的 C 程序在 Dev C++ 中运行,但在另一个编译器中出现段错误

c++ - 如何将包含在字符(字节)中的十六进制值转换为整数?

matlab - 我可以删除占位符变量以节省 Matlab 中的内存吗?

c++ - 在运行时从指向基类的指针获取对象的类型

jquery - 如何使用 Jquery 动态创建带有 append 文本的 ul li