views:

87

answers:

5

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 newPtr; /* 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 */
+1  A: 

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.

Bertrand Marron
A: 

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

Thomas Padron-McCarthy
A: 

strcmp is the function you are looking for.

mcdave
A: 

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

Konamiman
+4  A: 

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)
Travis
Ok, great, had in my mind in C it "automatically" compared a chararray since char = int.
Chris_45
yet it can't automatically compare an int array, so it makes sense actually.
Samuel_xL
char is an integer but it is not an 'int'.
nos