我已经学习 C 一个月了,我已经学会/记得函数是这样定义的:
return_type function_name( parameter list ) {
...body
}
但是在关于“列表 ADT”的讲座中,演示了如何制作和打印完整列表的示例代码中存在一些我从未见过的形式的代码(函数声明)。
...
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;
}
如有任何帮助,我们将不胜感激!
如果我在某些方面错了,请纠正我。谢谢
最佳答案
你很接近,但读错了。函数名称中没有诸如 *
之类的内容,只有类型才有。
这定义了一个函数,返回给定参数d的
类型 list*
(又名struct list*
,这是typedef
之前建立的) 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
您通常可以发现解引用运算符,因为它在返回类型说明符、参数或变量声明中都不是类型的一部分。在大多数其他情况下,它是取消引用运算符。
关于c - 'return type' 为标签的函数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66167152/