2016-04-13 13 views
0
typedef struct node 
{ 
    Record data; 
    struct node *next; 
}Node; 

Node *head = NULL; 

void addRecord(Record x) 
{ 
    Node *previousNode = NULL; 
    Node *newNode; 
    Node *n; 

newNode = (Node*)malloc(sizeof(Node)); 
newNode->data = x; 
newNode->next = NULL; 

if (head == NULL) // The list is empty 
{ 
    head = newNode; 
} 
else  // The list is not empty 
{ 
    n = head; 
    while (n->next != NULL) 
    { 
     ***if (n->data < newNode->data && n->next->data > newNode->data)*** // Insertion Sort 
     { 
      // We have to put it between these 2 nodes 
      newNode->next = n->next; 
      n->next = newNode; 
      return; 
     } 
     else 
     { 
      previousNode = n; 
      n = n->next; 
     } 
    } 
    n->next = newNode; 
} 

}C Fehler: Ausdruck muss arithmetische oder Zeigertyp

Ich habe diesen Fehler in dem Code innerhalb der Funktion, wenn der Insertionsort haben. Das Programm sagt, dass 'n' Arithmetik- oder Zeigertyp haben muss. Was scheint das Problem zu sein?

+0

[. Bitte lesen Sie diese Diskussion darüber, warum nicht den Rückgabewert von 'malloc()' und Familie in 'C' werfen] (http://stackoverflow.com/q/ 605845/2173917). –

+0

Ich bin mir fast sicher, dass die Fehlermeldung, die Sie gepostet haben, falsch ist. –

+0

In welcher Zeile erhalten Sie einen Fehler? Was ist die Definition von Typ Record? – MikeC

Antwort

1

Betreiber Überlastung ist nicht in C unterstützt, so können Sie Record mit > Betreiber nicht vergleichen, es sei denn es typedef ed zu int oder andere aritimetic oder Zeigertyp ist.

Um etwas wie Strukturen zu vergleichen, definieren Sie die Vergleichsfunktion und verwenden Sie sie.

Beispiel:

typedef struct { 
    int a, b; 
} Record; 

/* 
return positive value if *x > *y 
return negative value if *x < *y 
return 0 if *x == *y 
*/ 
int cmpRecord(const Record* x, const Record* y) { 
    if (x->a + x->b > y->a + y->b) return 1; 
    if (x->a + x->b < y->a + y->b) return -1; 
    return 0; 
} 

/* ... */ 
    while (n->next != NULL) 
    { 
     if (cmpRecord(&n->data, &newNode->data) < 0 && cmpRecord(&n->next->data, &newNode->data) > 0) // Insertion Sort 
     { 
/* ... */