[英]how to take a linked list and a function pointer as inputs
I am new to C and trying to learn function pointer.I am supposed to complete the 'map_list'function which takes a linked list and a function pointer,and return a new list in the same order, but with all the values squared.Please point it out where I did wrong. 我是C语言的新手,试图学习函数指针。我应该完成'map_list'函数,该函数接受一个链表和一个函数指针,并以相同的顺序返回一个新列表,但所有值均平方。指出我做错了的地方。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
struct Link {
struct Link *next;
int value;
};
void print_list(struct Link *list) {
for(struct Link *l = list; l != NULL; l = l->next) {
printf("%d", l->value);
if(l->next) {
printf(", ");
}
}
printf("\n");
}
struct Link *append(int x, struct Link *head) {
struct Link *head_ = (struct Link*)malloc(sizeof(struct Link));
head_->next = head;
head_->value = x;
return head_;
}
struct Link *reverse_list(struct Link *list) {
struct Link *head = NULL;
for(struct Link *l = list; l != NULL;) {
struct Link *next = l->next;
l->next = head;
head = l;
l = next;
}
return head;
}
struct Link *map_list(struct Link *link_list,int (*Square)(int) ) {
struct Link *new_list = NULL;
new_list = new_list ->next;
new_list ->value = (*Square)(link_list ->value);
return new_list;
}
int square(int x) {
return x * x;
}
int add3(int x) {
return x + 3;
}
struct Link *theList() {
struct Link *l = append(1, NULL);
l = append(2, l);
l = append(3, l);
l = append(5, l);
return l;
}
int main() {
struct Link *l = theList();
print_list(map_list(l, &square));
;
return 0;
}
I got 'Segmentation fault (core dumped)' 我收到“分段错误(核心已转储)”
If I have understood correctly you have some trouble with writing the function map_list
. 如果我正确理解,编写函数
map_list
遇到麻烦。 It can look the following way 它可以看起来如下
struct Link * map_list( const struct Link *link_list, int operation( int ) )
{
struct Link *new_list = NULL;
struct Link **new_node = &new_list;
for ( const struct Link *current = link_list; current != NULL; current = current->next )
{
*new_node = malloc( sizeof( struct Link ) );
( *new_node )->next = NULL;
( *new_node )->value = operation( current->value );
new_node = &( *new_node )->next;
}
return new_list;
}
And the function can be called for example like 函数可以像这样调用
map_list( l, square );
or 要么
map_list( l, add3 );
The function does not check whether a memory allocation for a node was successfull. 该功能不检查节点的内存分配是否成功。 You can add such a check yourself.
您可以自己添加这样的支票。
As for your own function implementation 至于你自己的功能实现
struct Link *map_list(struct Link *link_list,int (*Square)(int) ) {
struct Link *new_list = NULL;
new_list = new_list ->next;
new_list ->value = (*Square)(link_list ->value);
return new_list;
}
then for starters it has undefined behavior 那么对于初学者来说,它具有不确定的行为
ew_list = new_list ->next;
and does not make sense relative to the assignment. 并且相对于分配没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.