I am trying to learn about pointers in C, and don't understand why the unary * operator was appended to the end of the word "node" in the following code snippet:
struct node* CopyList(struct node* head) {
/* code here */
}
From my understanding of pointers, one can create a pointer with a statement like
int *pointerName;
and assign a "pointee" to it with a statement like
pointerName = malloc(sizeof(int));
and then dereference the pointer with a statement like
*pointerName = 4;
which will store the integer value 4 in the 4 bytes of memory (pointee location) which is "pointed to" by the pointerName pointer.
WITH THAT BEING SAID, what does it mean when the * is appended to the end of a word, as it is with
struct node*
???
Thanks in advance!
The location of the *
ignores the whitespace between the base type and the variable name. That is:
int* foo; // foo is pointer-to-int
int *bar; // bar is also pointer-to-int
In both cases, the type of the variable is "pointer-to-int"; "pointer-to-int" is a valid type.
Armed with that information, you can see that struct node*
is a type , that type being "pointer-to-node-structure". Finally, therefore, the whole line
struct node* CopyList(struct node* head)
means " CopyList
is a function taking a pointer-to- struct node
(called head
) and returning a pointer-to- struct node
"
struct node* CopyList
To understand better you should read it from right to left. Which says CopyList
is a function returning a pointer to node.
int *pointerName;
is the same as int * pointerName;
or int* pointerName;
. The data type is int*
in all those cases. So struct node*
is just a pointer to struct node
.
But it is suggested to use it with while declaring methods, like shown below 一起使用,如下所示
struct node* CopyList(struct node* head) {
/* code here */
}
when declaring pointers of a type use * with the 使用* like shown below,
int *ptr;
Declaring in that way increases readability.
For example consider this case,
int* a,b,c;
The above statement is appearing like declaring three pointer variables of base type integer, actually we know that it's equals to
int *a;
int b,c;
Keeping the * operator near the data type is causing the confusion here, So following the other way increases readability, but it is not wrong to use * in either way.
node*
表示以下函数/变量/结构的类型为“指向节点的指针”。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.