[英]Assigning a pointer in content of a pointer
In the code, we can see that a pointer is assigned in *new_node
.在代码中,我们可以看到在
*new_node
分配了一个指针。 But in C
*new_node
means content of new_node
.但在
C
*new_node
意味着内容new_node
。 So, what is the reason for it & why isn't it creating any problem?那么,它的原因是什么?为什么它不会造成任何问题?
Node *create_node(int item, Node *next)
{
Node *new_node = (Node *)malloc(sizeof(Node)); //isn't it receiving the pointer as content of(*new_node) new_node?
if (new_node == NULL) {
printf("Error! Could not crate a new Node\n");
exit(1);
}
new_node->data = item;
new_node->next = next;
}
Node *new_node = (Node *)malloc(sizeof(Node));
This allocates new dynamic memory for new element of Node struct.这会为 Node 结构的新元素分配新的动态内存。 And base address of the allocated memory is stored in new_node.
并且分配的内存的基地址存储在new_node中。
Now, new_node points to a new memory but that memory is empty/garbage.现在, new_node 指向一个新内存,但该内存是空的/垃圾。 It doesn't contain any useful information about the node.
它不包含有关节点的任何有用信息。 So we need to fill the necessary information it that structure to make it useful.
因此,我们需要在该结构中填充必要的信息以使其有用。
`new_node->data = item;`
new_node->next = next;
These lines copy the data to the allocated memory of new node and link the new node with other nodes.这些行将数据复制到新节点分配的内存中,并将新节点与其他节点链接起来。
NOTE: Your code snippet doesn't have return statement.注意:您的代码片段没有 return 语句。
In an expression *new_node
means “the object pointed to by new_node
.”在表达式中
*new_node
意思是“由new_node
指向的对象”。 However, Node *new_node = (Node *)malloc(sizeof(Node));
但是,
Node *new_node = (Node *)malloc(sizeof(Node));
is a declaration, not an expression statement, and the text *new_node
in it is not an expression.是声明,不是表达式语句,其中的文本
*new_node
也不是表达式。
The first part of the declaration, Node *new_node
, says “ new_node
is a pointer to a Node
.”声明的第一部分
Node *new_node
表示“ new_node
是一个指向Node
的指针。” The second part of the declaration, = (Node *)malloc(sizeof(Node))
, says “initialize new_node
to (Node *)malloc(sizeof(Node))
.声明的第二部分
= (Node *)malloc(sizeof(Node))
表示“将new_node
初始化为(Node *)malloc(sizeof(Node))
。 The =
in this is not an assignment, and this is not an assignment expression. this 中的
=
不是赋值,也不是赋值表达式。 It is a syntax used in declarations for specifying an initial value for the object being defined.它是在声明中使用的一种语法,用于为正在定义的对象指定初始值。 The object being defined is
new_node
, not *new_node
.被定义的对象是
new_node
,而不是*new_node
。
This is different syntax between declarations and assignments, and you will have to become accustomed to it.这是声明和赋值之间的不同语法,您必须习惯它。
Node *new_node = foo;
initializes new_node
to foo
, but *new_node = foo;
将
new_node
初始化为foo
,但*new_node = foo;
sets *new_node
to foo
.将
*new_node
设置为foo
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.