将结构Aliasname*用于C语言中的函数返回类型



我是C语言的新手!如果我的问题很简单,请原谅我。此外,我很感激能简单地解释我的问题,非常感谢。

我读到了C语言的列表,基于这个示例代码,他们试图创建一个列表函数:

typedef struct list{int data; struct list *next;} list;

list* creat_list(int d){
list* head = malloc(sizeof(list));
head ->data = d;
head ->next = NULL;
return head;
}

函数的工作方式对我来说很简单,但我不明白他们为什么使用list*作为函数返回类型,这到底意味着什么?到目前为止,我了解到list*意味着指向struct list的指针,但是,使用结构中的指针作为函数返回类型意味着什么?我怎么知道什么时候该用它呢?

如果代码的其余部分很重要,我会把它写在下面

#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* creat_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 = creat_list(d);
head ->next;
return head;
}
list* array_to_list(int d[], int size){
list* head = creat_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("%sn", title);
while(h != NULL){ //checker!
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, "multiple elements list");
printf("nn");

//  Commented code is for single element list
/*
head = malloc(sizeof(list));
printf("sizeof(list) = %lun", sizeof(list)); //long long ??
head -> data = 5;
head -> next = NULL;
print_list(head, "single element list");
printf("nn");
*/

return 0;
}

creat_list()为列表头(列表上的第一项(分配内存,并返回一个指向该列表的指针,以便将其传递给对该列表进行操作的其他函数。所以在使用中你可能会有:

List* mylist = creat_list( 1 ) ;
add_to_front( 2, mylist ) ;
add_to_front( 3, mylist ) ;    
add_to_front( 10, mylist ) ;

这里mylist被传递给add_to_front,这样它就知道它要添加到哪个列表。它允许你有多个列表:

List* Alist = creat_list( 1 ) ;
List* Blist = creat_list( 2 ) ;
add_to_front( 2, Alist ) ;
add_to_front( 3, Blist ) ;    

注意,只有当add_to_front()具有其名称所隐含的语义时,上述内容才有意义。你的问题中提出的函数并不能做到这一点。添加到单链表的并不简单,它显然只是为了添加到而设计的。

最新更新