首页 > 解决方案 > 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))

标签: c++pointers

解决方案


这个星号在类型名称之后。它的意思是“指向该类型的指针”,在这种情况下,指向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 代码。


推荐阅读