【问题标题】:Whats the difference between void function(stuct *s) vs void function(stuct s)?void 函数(stuct *s)与 void 函数(stuct s)有什么区别?
【发布时间】:2017-12-08 08:55:35
【问题描述】:

我有这个学校作业要做,但我被要求做的功能弄糊涂了。和我做单链表的风格不一样。

我做这样的单链表:

typedef struct structNode{
    int data;
    struct structNode *next;
} node;

typedef struct structList{
    int count;
    struct structNode *head, *tail;
} list;

void insertFront(list *L, int x);
void insertRear(list *L, int x);
void insertAt(list *L, int x, int p);
void deleteFront(list *L);
void deleteRear(list *L);
void deleteAt(list *L, int p);
void displayAll(list *L);

所有参数都接收一个指针,但我的作业需要我像这样执行我的代码:

typedef struct node *nodePtr;

struct node {
    int item;
    nodePtr next;
};

typedef nodePtr Statistician;

Statistician newStatistician();
  //allocates memory to the structure. Dynamic allocation
void destroyStatistician(Statistician *s);
  //destroys statistician
void add(Statistician s, int x);
  //Adds data to the rear
void remove(Statistician s, int x);
 //removes data
void displayData(Statistician s);

所以我很困惑有什么区别,因为我习惯了接收指针并且作业风格不同。

我认为带有接收指针的那个是通过引用调用的,这就是为什么我在本地编辑的内容可以全局编辑...

还有我的结构实现与我必须做的有什么不同?

【问题讨论】:

  • 您需要了解typedef struct node *nodePtr; 的含义。检查cdecl.org。
  • 符号Statistician 是一个类型名,是类型名nodePtr 的别名,而nodePtr 又是类型struct node * 的别名。所以Statistician 是一个指针类型。例如add 参数s 是 一个指针。这非常清楚地显示了定义指针类型别名的危险:它使代码变得不清晰,更难阅读、理解和维护。
  • @Jezreel Tan 我确信这个声明 void add(Statistician s, int x);是错的。相反,它应该看起来像 void add(Statistician *s, int x);
  • @Jezreel Tan :本练习引入information hiding 的合理性。这些用户的 Statistician.h 文件将不包含struct node { int item; nodePtr next; }; - 那里不需要。目标是使Statistician 成为opaque pointer type。

标签: c function pointers linked-list structure


【解决方案1】:

统计学家是一个指针。它被定义为 nodePtr,而 nodePtr 又被定义为 node*。所以传递一个 Statistician 就是传递一个节点*。

从可用性的角度来看,让指针看起来像非指针是否明智是另一个问题。

【讨论】:

  • “它是否聪明……是一个不同的问题”我认为答案是否定的。我认为这个问题很好地说明了为什么答案是否定的。
  • 当然不是,只是让您头疼。每次分配内存或任何东西或将其传递给函数时,您都必须查看标头以了解它到底是什么。
  • 顺便说一句,您能否在答案中添加一些内容来解释为什么destroyStatistician 的参数是指向Statistician 的指针,即使Statistician 已经是一个指针。
  • 非常正确。我能想到 typedef 指针的唯一原因是,如果您使用的是 C++ unique_ptr 或 shared_ptr,但这些又不是“真正的”指针。此外,typedef'ing 增加了可读性和可维护性。对指针进行类型定义,这样您就不必编写 *,这就像您可以做的最懒惰的事情,而且会直接造成混乱和适得其反。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 2012-07-01
  • 2010-12-14
相关资源
最近更新 更多