C错误: expression must have arithmetic or pointer type

标签 c pointers struct nodes insertion

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;
}

}

我在插入排序的 if 函数内的代码中遇到此错误。该程序表示“n”必须具有算术或指针类型。问题出在哪里?

最佳答案

C 中不支持运算符重载,因此您无法使用 > 运算符比较 Record,除非将其 typedef 编辑为 int 或其他算术或指针类型。

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

示例:

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

关于C错误: expression must have arithmetic or pointer type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36603870/

相关文章:

c++ - 二叉搜索树 - 制作字典

C:如何使用sizeof来分割一个字符?

C : "same file descriptors of all client connections" (client server programming)

c - 在 C 中返回 malloced 指针

c - 字符串转换为int

将 FILE 中的字符串与其他字符串进行比较

清除链接结构中的每个节点

c++ - 如何在 C++ 中遍历 void* 的字节?

c++ - 返回指向对象的指针(C++ 模板)错误

c - C 中不寻常的结构定义