Home > Back-end >  Indexing Error With Dynamically Allocated Array
Indexing Error With Dynamically Allocated Array

Time:09-18

I am working on a HW assignment dealing with a dynamically allocated array that can handle different sized input files. My issue is that a pair of (null) values keep appearing tied to the word_alloc variable (changing it moves where in the output the (null) appears). How do I fix this?

int main(int argc, char *argv[]) {
    char str[80];
    int word_alloc = 0;
    int word_count = 0;
    char **str_array;

    FILE *file;
    file = fopen("hw3-data.txt", "r");

    // Allocate memory to the array of strings (char arrays)
    word_alloc = 10;
    str_array = (char **) malloc(sizeof(char*) * word_alloc);

    while (fscanf(file, "%s", str) != EOF) { 
        //doubles the word_alloc/str_array if we have more words than allocated
        if(word_count > word_alloc) {
            word_alloc *= 2;
            str_array =(char **) realloc(str_array, sizeof(char*) * word_alloc);
        }

        str_array[word_count] = (char *) malloc(sizeof(char) * (strlen(str)   1));
        strcpy(str_array[word_count], str);
          word_count;
    }

    return 0;
}

here is the output

CodePudding user response:

The errors happen because you have array overflow. Change

if(word_count > word_alloc)

to

if(word_count >= word_alloc)

to fix it.

  •  Tags:  
  • c
  • Related