为什么 malloc 在分配内存时一直给出 "incompatible types" 错误,即使指针和类型转换都是正确的类型

Why does malloc keep giving a "incompatible types" error when assigning memory even though both the pointer and the typecasting are of correct type

void createLL(int A[], struct Node *a)
{
    struct Node* b, temp;

     a->data = A[0];
     a->next = NULL;
     b=a;

     for(int i=1;i < SIZE;i++)
     {
         temp = (struct Node*)malloc(sizeof(struct Node));
         temp->data = A[i];
         temp->next = NULL;
         b->next = temp;
         b =temp;
     }
}

错误:

1.37.0\LinlL.c:19:10: error: incompatible types when assigning to type 'struct Node' from type 'struct Node *'
temp = (struct Node *)malloc(sizeof(struct Node)); 
^
struct Node* b, temp;

应该是

struct Node *b, *temp;

在第一个版本中,temp是一个struct Node;即不是指针类型,因此当您尝试为其分配指针类型时,编译器会发出诊断信息。

流行的做法是将指针视为声明中类型的一部分而不是变量,但事实并非如此。对于单个变量声明没有区别,但是对于多个变量声明,就像这里的情况一样。

此外,在 C 中强制转换 malloc 的结果是不必要的(它在 C++ 中),甚至有时是有害的。

此声明中有错字

struct Node* b, temp;

其实就是下面的声明

struct Node* b;
struct Node temp;

即变量b声明为指针,而变量temp声明为结构类型的对象

你必须写

struct Node *b, *temp;

错字的原因是你在没有使用的范围内声明了变量temp。您应该在 for 循环中声明它。:)

在任何情况下该函数都是无效的因为原始节点(我认为是列表的头部)是按值传递给函数的。即该函数处理头节点的副本。变量a的副本的任何更改都不会影响原始节点头的值。

函数可以这样定义。

void createLL( const int A[], struct Node **a)
{
     for ( int i = 0; i < SIZE; i++ )
     {
         *a = (struct Node*)malloc(sizeof(struct Node));
         ( *a )->data = A[i];
         ( *a )->next = NULL;
         a = &( *a )->next;
     }
}

并称赞

struct Node *head = NULL;
int A[SIZE] = { /* some values */ };

// ...

createLL( A, &head );