Reputation: 959
I am having trouble with dynamic allocating. My program needs to take in a text file, take in each word, and put them into an array while counting repeated words. I think that I am malloc-ing the words into the array correctly, however I do not understand how to make an array with the struct I have created using dynamic allocating. i.e. it needs to grow as the list does. Thanks for any help you can give me. The areas that I have commented out are also areas of trouble.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned int uint;
typedef struct wordType
{
char * word;
uint count;
};
/* store the string in another temp string which you can iterate through
and compare with the array of non-repeated words. if there, increment*/
int main( void )
{
typedef struct wordType * WORD_RECORD;
WORD_RECORD arrayOfWords = malloc(10 * sizeof( WORD_RECORD) );
FILE * inputFile;
char temp[50];
uint i;
uint j;
uint size;
uint exists;
inputFile = fopen( "input.txt", "r");
if( inputFile == NULL )
{
printf( "Error: File could not be opened" );
/*report failure*/
return 1;
}
i = 0;
size = 0;
while( fscanf( inputFile, "%s", temp) == 1 )
{
exists = 0;
for( j = 0; j < size; j++ )
{
if( strcmp( arrayOfWords[j].word, temp ) == 0 )
{
arrayOfWords[j].count++;
exists = 1;
}
}
if( exists == 0 )
{
arrayOfWords[i].word = malloc(sizeof(char)
* (strlen(temp)+1));
strcpy( arrayOfWords[i].word, temp );
/*arrayOfWords[i].count++;*/
size++;
}
i++;
}
for( i = 0; i < (size-1) ; i++ )
printf("%s\n", arrayOfWords[i].word);
fclose( inputFile );
/*for( i = 0; i < size-1; i++ )
free( arrayOfWords[0].word );*/
return 0;
}
Upvotes: 0
Views: 110
Reputation: 5049
You appear to be using malloc()
correctly to initialize your arrayOfWords array. you can grow the array using the realloc()
function, but you'll have to keep track of how large it is any how many words you have, so you'll know when to call realloc()
. In the case of if ( exists == 0 )
, the variable arrayOfWords[i].count
hasn't yet been initialized, so assuming it is zero is a bug, attempting to increment it is a bug, and anything other than setting it to an explicit value (in this case, 0
), is a bug.
You appear to be using i
to count the total number of words you've read, not unique words you've read, so using i
as your loop counter when you print the words out is wrong as well. The same holds for when you're freeing the malloc()
'ed words: using i
as the loop counter means you end up free()
ing thing you didn't get from malloc()
.
To dynamically grow the storage for your list of words, you'll need to keep track of how many struct wordType
items you've allocated storage for, and when adding a new word, check if you've reached your limit, and realloc()
if necessary.
When looping to print (and to free) the words, why are you doing "size - 1" ?
Upvotes: 2