简体   繁体   中英

Using nodes in the function strcmp

I have a homework problem described in the quotes below. This is a simple function that I must implement. After looking online I just found functions with similar implementation but no explanation.

The program grading my code just says "wordCmp fails when used". So basically any advice on how to differently approach this? It's just that the grader gives such a broad response that I'm not sure what could be wrong with it.

int wordCmp (struct inode* n1, struct inode* n2)

Returns an integer indicating the relationship between the strings in two nodes: A value greater than zero indicates that the first character that does not match has a greater value in n1->word than in n2->word; And a value less than zero indicates the opposite. You can use strcmp to implement this function.

 struct inode { char *word; }; int wordCmp (struct inode* n1, struct inode* n2){ return strcmp(n1->word, n2->word); } 

Based on this edit by the question author the solution was:

I made pointers that equaled the value of the words in the nodes and then compared them. I don't know why it worked though honestly it seems the same to me.

It said in the handout that we couldn't access the nodes fields directly; not sure why..., so I just implemented the following code so I did not have to access it directly. It does the exact same thing...

 int wordCmp (struct inode* n1, struct inode* n2){ char* wordOne = nodeGetWord(n1); char* wordTwo = nodeGetWord(n2); return strcmp(wordOne, wordTwo); } nodeGetWord(struct lnode *node){ return node->word; } 

That is all I did and it worked... Sorry if this seems dumb but it is what the grader took.

Have you checked if they are equal? strcmp will return 0 if they are the same character string. From what you put up as the assignment it looks like you have the correct compare except when the strings are equal.

Add some logic to determine if the strings are the same, return a value that follows your sorting choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM