【问题标题】:what is '*' in struct fuction?结构函数中的“*”是什么?
【发布时间】:2019-11-18 08:01:37
【问题描述】:
struct Node *addToEmpty(struct Node *last, int data) 
{ 
  // This function is only for empty list 
  if (last != NULL) 
    return last; 

  // Creating a node dynamically. 
  struct Node *temp =  
       (struct Node*)malloc(sizeof(struct Node)); 

  // Assigning the data. 
  temp -> data = data; 
  last = temp; 

  // Creating the link. 
  last -> next = last; 

  return last; 
} 

struct Node *addBegin(struct Node *last, int data) 
{ 
  if (last == NULL) 
      return addToEmpty(last, data); 

  struct Node *temp =  
        (struct Node *)malloc(sizeof(struct Node)); 

  temp -> data = data; 
  temp -> next = last -> next; 
  last -> next = temp; 

  return last; 
} 

我想知道为什么使用“*addToEmpty”而不是“addToEmpty”。

结构中的“*”是什么意思?

我知道这是基本问题。但我找不到答案。

如果你回答我的问题,我今天会很充实

附:这是 C++ 代码。

【问题讨论】:

  • 返回类型为Node*(指向节点的指针)。试着这样读:struct Node* addToEmpty(struct Node *last, int data)
  • 查看函数的返回值。你返回一个指向节点的指针,返回类型是Node *<function_name>。对我来说,如果它写成Node* <function_name>,我会更喜欢它
  • 这比 C++ 更多的是 C
  • stackoverflow.com/questions/6990726/… 试图解释为什么(一些)C 程序员这样声明指针。
  • 相关:Use of '&' operator before a function name in C++。这里也是同样的问题,只是使用* 而不是&。它们都适用于返回类型,而不是函数名。

标签: c struct syntax


【解决方案1】:

这是 C(++) 的 A 和 B [双关语]。

在这个函数中,你返回一个指向节点结构的指针...

您要求我们教您指针的基础知识。看看https://en.cppreference.com/w/cpp/language/pointer 或谷歌“在 C++ 中使用指针”,都会得到解释。

【讨论】:

    【解决方案2】:

    只要改变你的阅读方式:

    • struct Node 意味着我们返回一个Node 类型的结构。在 c++ 中,struct 关键字不是必需的。

    • 现在 * 属于返回类型,而不是函数名。 struct Node * 是指向 Node 类型结构的指针

    • addToEmpty是函数名。

    如果你更清楚,你也可以写Node* addToEmpty。这里只是个人喜好问题,更清楚的是addToEmpty 返回一个Node*(指向Node 的指针)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      相关资源
      最近更新 更多