无法在C中打印Map / Filter / Reduce功能

时间:2012-04-14 20:38:12

标签: c++ c visual-studio-2008 unhandled-exception

我很难理解为什么我一直得到一个异常,当我的函数轻松返回值时,但是一旦我尝试printf结果它给了我一个未处理的异常错误(见下文)我是C的新手,所以我一直在从java的角度看待一切,我无法弄明白。

继承我的相关代码(reduce接受一个链表,这是一个包含int值的节点数组,以及指向列表中下一个节点的指针,最后一个节点指向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
else
{
    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;
    }
    else{
        second = first->next;
    }

}

}

在main中我传递一个指向sum的函数的指针,它只是将两个值加在一起

简单代码

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


result = reduce(sum, newLink, 0);

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

现在所有人都抛出了这个VVVVVVVV

  

ExamTwo.exe中0x1029984f处的未处理异常:0xC0000005:访问冲突读取位置0x00000015。

2 个答案:

答案 0 :(得分:3)

你的reduce()函数返回一个int,但你给printf()一个字符串的格式代码。尝试

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

答案 1 :(得分:0)

您需要在printf中将%s替换为%d。