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.0LinlL.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 );