c++ - c++中变量前面的星号是什么?
问题描述
我目前正在学习链表,我的教授给我们发了一个对我来说很难理解的代码。我知道在变量之前使用星号以使其成为指针,但这个星号在变量的前面。
这是代码:
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node *head = NULL;
void insert(int new_data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = head;
head = new_node;
}
void display() {
struct Node* ptr;
ptr = head;
while (ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: ";
display();
return 0;
}
这是我正在谈论的一个:
void insert(int new_data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = head;
head = new_node;
}
我不知道这里星号的用途是什么(struct Node*) malloc(sizeof(struct Node));
\
有人能告诉我 malloc 的目的是什么吗malloc(sizeof(struct Node))
解决方案
这个星号在类型名称之后。它的意思是“指向该类型的指针”,在这种情况下,指向struct Node
.
让我们把这行代码看成一个整体:struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
在这里,声明了一个变量new_node
,它的类型为“pointer to struct Node
”。该函数malloc
分配一块内存并返回一个指向它的指针。但是,它不知道指针的类型,因此将其返回为void*
(指向未知事物的指针)。
这就是为什么您需要在分配之前将其转换为正确的类型。(struct Node*)
是一个强制转换表达式,它将指针的类型更改为“指向的指针struct Node
”。
综上所述,这行代码分配了一块内存来存储struct Node
,并将其地址保存在new_node
变量中。
但是,是的,正如其他人所指出的,它不是 C++ 代码,而是 C 代码。
推荐阅读
- javascript - 如何在firestore中一次更新多个集合中的值?
- c# - 使用 cosmos db 在社交媒体应用程序中删除关于删除帖子的评论的正确方法
- python - 为什么我收到此错误“WSGIRequest”对象没有属性“kwargs”?
- python - 返回分配有不同值的名称
- sql - SQL 查询:User/Group/Role 和 UserGroup/GroupRole 将用户连接到角色
- rust - 如何从 vec 中的枚举中获取值?
- javascript - 如何模块化使用constructor.prototype的javascript函数?
- mysql - 在 wordpress 中显示 mysql 字符串输出
- html - 移动导航栏切换器未出现在 500 像素的最大宽度中
- javascript - 如果列标题发生冲突,希望在 html 表上动态设置最小宽度