当我的函数轻松返回值时,我很难理解为什么我不断收到异常,但是一旦我尝试 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。