0

so I'm having a little problem with my struct array not doing what its supposed to. I get no compiler warnings or errors when building the program.

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;
}

These functions get called from a different file, The Add_To_Array is called when the program reads a new word form the text file. That function is supposed to check if the word already exists in the struct array and if it does, it should just increment the counter. If it doesn't, then it adds it.

The Print_All function is called after all the words have been stored in the struct array. Its supposed to loop through them and print each word and their occurrence. In the text file, there are 2 of every words but my program outputs:

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

I don't know what to make of this as im really new to C programming... It's probably worth mentioning the if(Word_Foun==0) doesn't execute

1
  • Don't use global variables when they are not needed. Modify your functions so that you can pass the length of array instead of using a global variable for the length. Commented Feb 21, 2018 at 21:11

1 Answer 1

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

This will be the correct allocation. Otherwise you will have erroneous behavior in your code. Also check the return value of malloc.

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

You are allocating for struct WordElement not a for a pointer to it. You already have a pointer to struct WordElement all that you needed was memory for a struct WordElement.

Also in the loop you are accessing array index out of bound

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

It will be i < Array_Size.

In case match occurs you want to set the variable Word_found to 1.

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

Also Writer = fopen(File_Name, "w"); you should check the return value of fopen.

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

Also when you are increasing the Array_index place a check whether it might access the array index out of bound.

The more global variable you use for achieving a small task would make it more difficult to track down a bug. It is always problematic because the places from which data might change is scattered - making it difficult to manage.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your analysis, edited all of the things you said yet my code still doesn't execute the if(Word_Found==0) statement and the output is still the same. What am I doing wrong there? I
@Hunt3R.: Well that means there is something more that can't be decided from the code you have shown. Use a debugger if you know how to, a suggestion - write small parts first and don't use that many global variables. I am curious whether you have added all the modifications mentioned. If you did - it will show you atleast the errors.
I checked my code again and when allocating the memory, it allocates enough for all the words, including the duplicates, so I created another variable that only increments if a new word is being added. I used said variable for the printing loop and now it prints the words fine (one extra is added for some reason, a mix of 2 words) but the count is still not printing properly. ALSO, when i run the program for the 2nd time (or more) I get the error 'A heap has been corrupted', am i not freeing the memory properly?
@Hunt3R.: It is some problem with allocation and freeing them. Can you use valgrind? It will help you detect the problem. If you can't - then ask a question with modified code and the error you got. Also explain what you tried to solve the problem reading the error message. Somebody or me will answer the question.
fixed it by changing malloc to : StructPointer = malloc((Size * sizeof(StructPointer)+1)); and the ints weren't printing properly as i was trying to increment the counter without initializing it. Fixed that by setting the count to 1 when a new word was added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.