[英]Using struct Aliasname* for a function return type in C language
我是 C 語言的新手。 如果我的問題很簡單,請原諒我,而且,我很感謝我的問題的簡單解釋。 太感謝了。
我正在閱讀 C 語言中的列表,並且基於此示例代碼,他們正在嘗試創建列表 function:
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;
}
function 的工作方式對我來說很簡單,但我不明白他們為什么使用list*
作為 function 返回類型,這到底意味着什么? 到目前為止,我了解到, list*
表示指向struct list
的指針,但是,將 struct 中的指針用於 function 返回類型意味着什么? 我怎么知道什么時候應該使用它?
如果代碼的rest很重要,我寫在下面
#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("%s\n", 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("\n\n");
// Commented code is for single element list
/*
head = malloc(sizeof(list));
printf("sizeof(list) = %lu\n", sizeof(list)); //long long ??
head -> data = 5;
head -> next = NULL;
print_list(head, "single element list");
printf("\n\n");
*/
return 0;
}
creat_list()
為鏈表頭(鏈表上的第一項)分配 memory,並返回指向該鏈表的指針,以便將其傳遞給對鏈表進行操作的其他函數。 所以在使用中你可能有:
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()
具有其名稱所暗示的語義時,上述內容才有意義。 您問題中提出的 function 並沒有這樣做。 添加到單鏈表的前面並不簡單,它顯然只是為了追加到末尾而設計的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.