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.
#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)'
struct Link *new_list = NULL;andnew_list = new_list ->next;. How will that work? And for the rest of the function, how would a new list be created (or the original modified) without any iteration?struct Link *head_ = (struct Link*)malloc(sizeof(struct Link));1) the returned type isvoid*which can be assigned to any pointer. Casting just clutters the code, making it more difficult to understand, debug, etc. 2) always check (!=NULL) the returned value to assure the operation was successful.struct Link *reverse_list(struct Link *list) {Your question did not mention anything about reversing the order of the list, so why this function? Please post a minimal reproducible example#include <stdbool.h>#include <string.h>and#include <ctype.hcontentorusage(or better, both) Names likelare meaningless, even in the current context