C错误:表达式必须具有算术或指针类型

时间:2022-09-13 17:04:40
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;
}

}

}

I have this error in the code within the if function of the insertion sort. The program says that 'n' must have arithmetic or pointer type. What seems to be the problem?

我在插入排序的if函数的代码中有这个错误。程序说'n'必须有算术或指针类型。有什么问题吗?

1 个解决方案

#1


1  

Operator overload is not supported in C, so you cannot compare Record using > operator unless it is typedefed to int or other aritimetic or pointer type.

C不支持操作符重载,因此不能使用>操作符比较记录,除非它被类型为int或其他aritimetic或指针类型。

To compare something like structures, define comparation function and use it.

要比较结构之类的东西,请定义比较函数并使用它。

Example:

例子:

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
        {
/* ... */

#1


1  

Operator overload is not supported in C, so you cannot compare Record using > operator unless it is typedefed to int or other aritimetic or pointer type.

C不支持操作符重载,因此不能使用>操作符比较记录,除非它被类型为int或其他aritimetic或指针类型。

To compare something like structures, define comparation function and use it.

要比较结构之类的东西,请定义比较函数并使用它。

Example:

例子:

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
        {
/* ... */