c 结构数组,存储字符串及其出现并将其写入文件

c Struct Array, Storing string and its occurrence and writing it to a file

所以我的结构数组有点问题,没有按预期执行。我在构建程序时没有收到编译器警告或错误。

int Array_Size=0;;
int Array_Index=0;
FILE *Writer;
struct WordElement
{
    int Count;
    char Word[50];
};

struct WordElement *StructPointer; //just a pointer to a structure

int Create_Array(int Size){
StructPointer = (struct WordElement *) malloc(Size * sizeof(StructPointer));
Array_Size = Size;
return 0;
}

int Add_To_Array(char Word[50]){
    int Word_Found=0;
    for(int i=0; i <= Array_Size && Word_Found!=1; i++)
    {
        if(strcmp(StructPointer[i].Word, Word)) // This should only run if the word exists in struct array 
        {
            StructPointer[i].Count++;
            Word_Found=1;

        }

    }
    if(Word_Found==0) // if the above if statement doesnt evualate, this should run 
    {
        strcpy(StructPointer[Array_Index].Word, Word); //copying the word passed by the main function to the struct array at a specific index
        printf("WORD: %s\n", StructPointer[Array_Index].Word); // printing it just to make sure it got copied correctly
        Array_Index++;
    }

    return 0;
}

int Print_All(char File_Name[50])
{
    Writer = fopen(File_Name, "w");
    printf("Printing starts now: \n");
     for(int i=0; i < Array_Size; i++)
    {
        fprintf(Writer, "%s\t\t%d\n",StructPointer[i].Word, StructPointer[i].Count);

    } 
    free(StructPointer);
    return 0;
}

这些函数从不同的文件中调用,当程序从文本文件中读取新单词时调用 Add_To_Array。该函数应该检查该单词是否已存在于结构数组中,如果存在,它应该只增加计数器。如果没有,则添加它。

Print_All函数在所有单词都存储到struct数组后被调用。它应该遍历它们并打印每个单词及其出现。在文本文件中,每个单词都有 2 个,但我的程序输出:

    this        13762753
document        -1772785369
contains        1129268256
two     6619253
of      5701679
every       5570645
word        3342389
doccontains     5374021

我不知道这是怎么回事,因为我是 C 编程的新手...可能值得一提的是 if(Word_Foun==0) 不执行

StructPointer =  malloc(Size * sizeof(*StructPointer));

这将是正确的分配。否则你的代码中会有错误的行为。还要检查 malloc 的 return 值。

StructPointer =  malloc(Size * sizeof(*StructPointer));
if(NULL == StructPointer){
   perror("malloc failure");
   exit(EXIT_FAILURE);
}

您分配的是 struct WordElement 而不是指向它的指针。您已经有了一个指向 struct WordElement 的指针,您所需要的只是 struct WordElement.

的内存

同样在循环中,您正在越界访问数组索引

for(int i=0; i <= Array_Size && Word_Found!=1; i++)
               ^^^

会是i < Array_Size

如果发生匹配,您希望将变量 Word_found 设置为 1

if(strcmp(StructPointer[i].Word, Word) == 0){
     /* it macthed */
}

另外 Writer = fopen(File_Name, "w"); 你应该检查 fopen 的 return 值。

  if(Writer == NULL){
     fprintf(stderr,"Error in file opening");
     exit(EXIT_FAILURE);
  }

此外,当您增加 Array_index 时,请检查它是否可能越界访问数组索引。

用于完成小任务的全局变量越多,跟踪错误就越困难。这总是有问题的,因为数据可能发生变化的地方是分散的——因此很难管理。