【发布时间】:2012-04-26 18:46:51
【问题描述】:
当我的函数轻松返回值时,我很难理解为什么我不断收到异常,但是一旦我尝试打印结果,它就会给我一个未处理的异常错误(见下文) 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
ExamTwo.exe 中 0x1029984f 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000015。
【问题讨论】:
-
result的类型是什么?您告诉 printf 它是一个字符串,但从阅读您的代码来看,它看起来像一个 int。 printf 会将result视为 char*
标签: c++ c visual-studio-2008 unhandled-exception