I need to create a dynamic array of a struct wordStruct
that holds a string and the number of times it occurs in a text file:
typedef struct wordStruct{
char word[50];
int count = 0;
}wordStruct;
I will get the number I need from reading the number of words in the file, let's call it wordCount
.
struct wordStruct *wordList;
wordList = (wordStruct *)malloc(wordCount * sizeof(wordStruct));
Is this the correct way to allocate the memory for struct
array? Would calloc()
be a better option?
int wordListIndex = 0;
char[50] inWord; // No word will be more than 49 characters + null terminator
for (i = 0; i < wordCount; i++){
fscanf(data, "%s", inWord);
for (j = 0; j < wordCount; j++){
if (strcmp(wordList[j].word, inWord) == 0){
wordList[j].count++;
break;
}
}
if (j == wordCount){
strcpy(wordList[wordListIndex].word, inWord)
wordListIndex++;
}
I know that this probably isn't the most efficient code, but do I have the right idea? Can I use the strcmp()
method even though there may not be any data in those array locations? I'm new to structs and I'm not sure what I can and cannot do.
Thanks.
If you use malloc
, you need to initialize the array (e.g., using memset
). If you use calloc
, the array is initialized to 0 for you.
Once the array is initialized, you can use strcmp
on it, because setting it to 0 makes all the words be zero-length (empty) strings. Before initializing it, you must not use strcmp
.
(I'm assuming the weird char[50] varname
instead of char varname[50]
are typos in your SO question, else this wouldn't compile. I'm also ignoring the buffer overflow in fscanf
and strcpy
… well, technically, I guess I'm not. And the lack of error handling.)