开发者

Comparing chararrays in linked list in the C programming language

How do you compare and sort chararrays in a linked list, cant you compare like this 'Smith' > 'Andersson' ?

struct person {
char name[20];
struct person *nextPerson;
};

.
void createNode(PersonPtr *sPtr, struct person t[]){
  PersonPtr ne开发者_如何学编程wPtr; /* pointer to new node */
  PersonPtr previousPtr; /* pointer to previus node in  list */
  PersonPtr currentPtr; /* pointer to current node in list */
.
/* loop to find correct location in the list */
while (currentPtr != NULL && t->name > currentPtr->name) { /* this will not sort on name */
  previousPtr = currentPtr; /* walk to... */
  currentPtr = currentPtr->nextPerson; /* ...next node */
}/* end while */


Close, but not quite, you can't just use ">" or "<" on strings. What you want is strcmp.

What you want is:

while (currentPtr != NULL && strcmp(t->name,currentPtr->name) > 0)


man strcmp(3)

Edit: Your variable t->name is a pointer to a char. When you do t->name > currentPtr->name you're comparing their values, i.e the chars addresses.


No, you can't just use the > operator. You need to call the library function strcmp.


strcmp is the function you are looking for.


If by "chararrays" yo mean "strings", you can compare them by using strcmp.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜