mercredi 23 septembre 2015

Random characters from memory when reading from file using fscanf

        //create the array from file
        char *array[100];
        char string[80];
        FILE * file;
        file = fopen( "file.txt" , "r");
        if (file) {
            int k = 0;
            while (fscanf(file, "%s", string)!=EOF){
                array[k] = strdup(string);
                k++;
            }                            
            fclose(file);
        }

        //print the history array for debugging
        for(int k = 0; k<sizeof(array); k++){
            printf("the element at %d is: %s\n", k, array[k]);
        } 

The resulting array has random characters from memory which are not present in the file. Is there any way to prevent this?

This is the result of the printf: http://ift.tt/1KBLjrK




Aucun commentaire:

Enregistrer un commentaire