c - 'return type' 为标签的函数有什么作用?

标签 c function

我已经学习 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/

相关文章:

python-3.x - python : How do I alias a function with specific parameters?

function - 为什么 SubString Vector 的一个元素不能被测试为条件评估 if (Julia)?

javascript - 为什么我在单独的 .JS 页面上设计的 ID 类不起作用

c - 十六进制参数 "or"| C 中的运算符

将链表复制到另一个链表 - 迭代 - C - 理解返回的列表

c - 我正在尝试将压缩的 rtp 数据包解码为 evs 并将其转换为 wav 文件

c - 使用二维数组存储多个字符串

链表中的字符数组导致核心转储

c# - 将参数传递给 AsyncCallback 函数?

c - 如何在 C 中调用(不定义)具有可变参数的函数?