我正在遵循this C教程,并且正在上关于链表的课程,但是我有些困惑。第一个代码块具有以下内容:
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main()
{
/* This will be the unchanging first node */
struct node *root;
/* Now root points to a node struct */
root = (struct node *) malloc( sizeof(struct node) );
/* The node root points to has its next pointer equal to a null pointer
set */
root->next = 0;
/* By using the -> operator, you can modify what the node,
a pointer, (root in this case) points to. */
root->x = 5;
}
让我感到困惑的那一行是root = (struct node *) malloc( sizeof(struct node) );
。因为在下面,所以还有另一个代码块:
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main()
{
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;
root = malloc( sizeof(struct node) );
root->next = 0;
root->x = 12;
/* rest of main */
return 0;
}
在此块中,他们有root = malloc( sizeof(struct node ) );
!为什么他们在最上面的块中键入强制转换malloc
而不是第二个?有区别吗?