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

Trying to do dynamic memory allocation in words (text) from file in c

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

#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 and you should also take a look at this