1

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

1 回答 1

1

在其中定义所有这些结构和函数main并不是您应该编写C的方式。将int main(int argc, const char *argv[]) {移到定义之后的右侧,printList以便main仅包含main.

此外,您的定义map似乎有一个未完成的原型。而不是void map(int (*func)(int v), struct linkedList), 其中第二个参数未使用,您想要void map(int (*func)(int v), struct linkedList* head)(然后摆脱head下一行的声明)。而且,linkedList2这里想必应该改成linkedList. 此外,你打电话的尝试mapmain荒谬map(square, linkedList)的;你想用map(square, head).

于 2012-04-12T21:41:59.987 回答