当我的函数轻松返回值时,我很难理解为什么我总是收到异常,但是一旦我尝试打印结果,它就会给我一个未处理的异常错误(见下文) 我是 C 的新手,所以我一直在从 java 的角度看待一切,但我无法弄清楚。
这是我的相对代码(reduce需要一个linkedlist,这是一个包含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
考试二.exe 0x1029984f处未处理的异常: 0xC0000005:访问违规读取位置0x00000015。
你的 reduce() 函数返回一个 int,但你给 printf() 一个字符串的格式代码。尝试
printf("Total is : %d", result );
在 printf 中将 %s 替换为 %d。