-
Comparing strings
So, I've been struggling for a while now figuring out how to properly compare strings. I have
Code:
typedef struct {
char word[101];
int freq;
} WordArray;
static WordArray *words[10000];
What do I use to compare with the word in WordArray?
I've tried
char tempWord[101];
tempWord = words[0]->word
I've also tried the above except
char *tempWord[101];
gives me problems.
I tried both of the above with just regular assignment
tempword = words[0]->word;
And many more. Any help appreciated. It would help if it was an array of temporary words but I just cant get that going >_>
-
None of those would be a comparison. At best you are assigning. To compare two strings, use strcmp, which is basically just a loop that loops through each character one at a time to see if they are equal.
Quzah.
-
I may be completely off-base here, but isn't it a better idea to do dynamic allocation (instead of fixed 10k), or:
Code:
typedef struct {
char word[101];
int freq;
} WordArray;
struct word_holder {
struct *wordArray[10000]; /* this way, you won't be using 80 kilobytes of the stack just to hold pointers */
};
struct word_holder *array; /* just allocate this regularly */
-
Sorry, I forgot to include that strcmp gives me problems too
-
You should use strcpy instead of = as in:
strcpy(tempword,words[0]->word).
Check this out for more info:
Dystopian Code: Concatenating, Copying and Comparing Strings in C
-
Code:
typedef struct {
char word[101];
int freq;
} WordArray;
static WordArray *words[10000];
That is an array of pointers to structures. You don't actually have any structures allocated. But if you did, it would compare something like this:
Code:
if( strcmp( words[ x ]->word, words[ y ]->word ) == 0 )
... they are the same
If you made that an array of structures instead of pointers to structures, then it would be:
Code:
if( strcmp( words[ x ].word, words[ y ].word ) == 0 )
... they are the same
Both of those assume you have actually copied something into 'word':
Code:
strcpy( words[ x ]->word, "hello" );
strcpy( words[ y ]->word, "world" );
Quzah.
-
But if I wanted to compare a non structure string to a structure one? strcpy(tempword,words[0]->word)? How would my tempword be declared?
char tempWord[101]; Would this suffice?