So here’s my code… My understanding is that I’m supposed to create a function “map” that takes a function as an argument. It’s not going as planned. Any help would be completely amazing.
Here’s a compilable (well not compilable, but scaled down) version of the code:
#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;
}
Defining all of those structs and functions inside of
mainis not how you’re supposed to write C. Move theint main(int argc, const char *argv[]) {to right after the definition ofprintListso thatmainonly contains the actual code formain.Moreover, your definition of
mapappears to have an unfinished prototype. Instead ofvoid map(int (*func)(int v), struct linkedList), in which the second parameter is unused, you wantvoid map(int (*func)(int v), struct linkedList* head)(and then get rid of the declaration ofheadon the next line). Moreover,linkedList2here presumably should be changed tolinkedList. In addition, your attempt to callmapinmainwithmap(square, linkedList)is nonsensical; you want to usemap(square, head).