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

标签 c pointers mapreduce

这是我的代码...我的理解是我应该创建一个函数“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/

相关文章:

c++ - shared_ptr with = symbol not allowed

caching - Hadoop——数据 block 缓存技术

谁能看出这有什么问题(C 中与时间相关的函数)

c - 以下程序中用于字符串比较的段错误

c - 为什么在尝试输入字符串时出现段错误?

C++ -- 指向数组的指针 -- 指针数组

c++ - OOP C++、虚函数和新运算符

c - 查找结构体数组 C 的大小

javascript - 以下 JavaScript reduce 函数的模式是什么?

hadoop - 在级联中删除 outputPath