gpt4 book ai didi

c - 链表上的 map/reduce/filter... map 失败! (在 C 中)

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:32 26 4
gpt4 key购买 nike

这是我的代码...我的理解是我应该创建一个函数“map”,它将一个函数作为参数。它没有按计划进行。任何帮助都会非常棒。

这是代码的可编译(当然不可编译,但按比例缩小)版本:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
int main(int argc, const char *argv[])
{
//it should be apparent that I am quite new to C, I have some java experience.
struct linkedList {
int count;
int num;
struct linkedList *next;
};
struct linkedList *head, *tail, *curr;
int count1=0;
int i=0;

int square(int v) {return v=v*v;}

void map(int (*func)(int v), struct linkedList){
struct linkedList2 *head, *tail, *curr;
for(curr=head; curr!=NULL; curr=curr->next){
curr->num=func(curr->num);
printList();
}
}

void start(){
printf("This program will ONLY accept integer input.\n");
head=NULL;
for(i=1;i<=4;i++) {
count1++;
curr=malloc(sizeof(struct linkedList));
curr->count=count1;
printf("Enter a number: ");
scanf("%d", &curr->num);
if(head==NULL) { head=curr; }
else { tail->next=curr; }
tail=curr;
tail->next=NULL;
}
printf("A list has been created.\n");
}

void printList(){
printf("The list now contains these numbers: ");
for(curr=head;curr!=NULL;curr=curr->next){
printf("%d, ", curr->num);
}
printf("\n");
}

start();
printList();

map(square, linkedList);
printList();
system("PAUSE");
return 0;
}

最佳答案

main 中定义所有这些结构和函数不是你应该如何编写 C。移动 int main(int argc, const char *argv[]) { 紧跟在 printList 的定义之后,这样 main 就只包含 main 的实际代码。

此外,您对 map 的定义似乎有一个未完成的原型(prototype)。而不是 void map(int (*func)(int v), struct linkedList),您需要 void map(int (*func)(int v ), struct linkedList* head)(然后去掉下一行的head声明)。另外,这里的linkedList2估计应该改成linkedList。此外,您尝试使用 map(square, linkedList)main 中调用 map 是荒谬的;你想使用 map(square, head)

关于c - 链表上的 map/reduce/filter... map 失败! (在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com