c - “返回类型”是标签的函数有什么作用?
问题描述
我已经学习 C 一个月了,我已经学会/记得函数是这样定义的:
return_type function_name( parameter list ) {
...body
}
但是在关于“list ADTs”的讲座中,演示制作和打印完整列表的示例代码中有一些我从未见过的形式的代码(函数声明)。
...
typedef struct list{ int data; struct list *next; } list;
list* create_list(int d) {
...
}
据我了解,返回类型是'list'(?),它是一个结构标记,函数名称是'* create_list'(这是一个取消引用的指针??)。我不明白为什么会这样写。我想知道它是如何工作的以及如何使用它。它与其他(正常外观)功能有何不同struct create_list(int d) {...}
?教练没有提及或解释这些,所以我很困惑。
这是完整的代码以防万一
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
typedef struct list{ int data; struct list *next;} list;
int is_empty(const list *l) { return (l == NULL); }
list* create_list(int d) {
list* head = malloc(sizeof(list));
head -> data = d;
head -> next = NULL;
return head;
}
list* add_to_front(int d, list* h) {
list* head = create_list(d);
head -> next = h;
return head;
}
list* array_to_list(int d[], int size) {
list* head = create_list(d[0]);
int i;
for(i = 1; i < size; i++) {
head = add_to_front(d[i], head);
}
return head;
}
void print_list(list *h, char *title) {
printf("%s\n", title);
while (h != NULL) {
printf ("%d :", h -> data);
h = h -> next;
}
}
int main() {
list list_of_int;
list* head = NULL;
int data[6] = {2,3,5,7,8,9};
head = array_to_list(data, 6);
print_list(head, "single element list");
printf("\n\n");
return 0;
}
任何帮助,将不胜感激!
如果我在某些方面错了,请纠正我。谢谢
解决方案
你很接近,但读错了。函数名没有类似*
的东西,只有类型有。
这定义了一个函数,它返回list*
(也struct list*
就是typedef
前面建立的)给定d
类型的参数int
:
list* create_list(int d) {
// ...
}
换句话说,create_list
返回一个指向 的指针list
。在类型定义*
中表示指针,但作为运算符具有不同的含义,例如:
int x = 0;
int* y = &x;
*y = 5; // Dereference y pointer, make assignment, in other words, assign to x
您通常可以发现取消引用运算符,因为它不是返回类型说明符、参数或变量声明中的类型的一部分。在大多数其他情况下,它是取消引用运算符。
推荐阅读
- python - 是否可以在 python 中训练卷积神经网络并将训练后的网络转换为 c 代码?
- python - 如何在 Ray 中使用 python 日志记录?
- python - 验证日期的简单方法,无论其格式如何
- unity3d - 无法在实例化的预制件上启动协程
- android - gradlew installdebug 显示命令的语法不正确
- javascript - Npm 启动失败
- ruby-on-rails - ActiveRecord 无法检索某些列
- java - 如何使用 Java 选择模态表单并在输入字段中输入数据
- javascript - 向带有动画的图像添加水平滚动条?
- angular - 如果我手动设置块,如何让 WorkboxPlugin 缓存我的 index.html?