Trouble printing Map/Filter/Reduce functions in C


I'm having a really hard time understanding why I keep getting an exception, when my function returns the value with ease, but once i try to printf the result it gives me an unhandled exception error(see below) I'm new to C so I've been looking at everything from a java perspective and I cant figure it out.

Heres my relative code (reduce takes a linkedlist, which is an array of nodes containing an int value, and a pointer to the next node in the list, the last node points to null)

int reduce(int (*func)(int v1, int v2), LinkedListP list, int init){

int i, sum;
struct node *first, *second;

sum = 0;
first = list->head;
second = list->head->next;

for(i = 0;i < list->count; i+=2)
//checks to see if there are values in the list at all
if(first == NULL)
    return sum;
//if first value is good, and the second value is null, then sum the final one and return the result
else if(second == NULL)
    sum += func(first->value, init);
        return sum;

//otherwise there is more to compute
    sum += func(first->value, second->value);

    //first now points to the next node that seconds node was pointing to
    first = second->next;

    //if the first link is null, then there is no need to assign something to the second one
    if(first == NULL){
        return sum;
        second = first->next;



and in main I pass a pointer to a function called sum which just adds two values together

simple code

newLink = new_LinkedList();
int(*reduceFunc)(int, int);
reduceFunc = sum;

result = reduce(sum, newLink, 0);

printf("Total is : %s", result );

now that all throws this VVVVVVVV

Unhandled exception at 0x1029984f in ExamTwo.exe: 0xC0000005: Access violation reading location 0x00000015.

asked on Stack Overflow Apr 14, 2012 by dannyRods

2 Answers


Your reduce() function is returning an int, but you're giving printf() the format code for a string. Try

printf("Total is : %d", result );
answered on Stack Overflow Apr 14, 2012 by mjfgates

You need to replace %s with %d in the printf.

answered on Stack Overflow Apr 14, 2012 by Michael Daum

User contributions licensed under CC BY-SA 3.0