c - 检查 C 中数组的值时出现未处理的异常

标签 c arrays recursion unhandled-exception

我有一个作业要编写一个递归程序,该程序获取一个数组(我们称之为 arr1)、数组的大小 (n) 和一个值。 程序将检查数组中是否有两个数字,以便它们的总和为 s。 例子 如果数组为 {1,3,2,0,5} 且 s=7,则该函数将打印“yes”,因为 5+2=7。 如果数组为 {1,3,2,0,5} 且 s=9,则该函数将打印“no”。没有任何一对的总和等于 9。

我的算法是这样工作的: 我计算数组中最后一个点(arr1[n-1])与其他每个点的摘要。如果我发现一对夫妇的总和是 s,那就太好了,打印 yes 并离开。 如果我没有找到,那么我会做同样的事情,但是我检查 arr1[n-2] 而不是 arr1[n-1]。我删除了最后一个位置。

这是我的代码:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void input_array_dyn(int* a, int n);
void rec(int* a,int n, int s);
void main()
{
    int n=0,s=0;
    int* a;
    printf("Enter value S\n");
    scanf("%d",&s);
    printf("Enter the size of the array\n");
    scanf("%d",&n);
    a=(int*)calloc(n,sizeof(int));
    printf("Enter %d values for the array\n",n);
    input_array_dyn(a,n);
    rec(a,n,s);
    free(a);
    getch();
}
void input_array_dyn(int* a,int n)
{
    int i=0;
    for(i=0;i<n;i++)
        scanf("%d",a[i]);
}
void rec(int* a,int n, int s)
{
    int i;
    if(n==1)
    {
        printf("There are no 2 number whos summary yields S\n"); 
        return;
    }
    for(i=0;i<n-1;i++)
    {
        if(a[n-1]+a[i]==s)
        {
            printf("There are two numbers that give s\n");
            return;
        }
    }
    rec(a,n-1,s);
}

我收到一条错误消息:“Test.exe 中 0x5846e30e (msvcr100d.dll) 处出现未处理的异常:0xC0000005:写入位置 0x00000000 时出现访问冲突。”

还有:有没有人有更好的算法来做到这一点? :)

最佳答案

input_array_dyn()中:

scanf("%d", a[i]);

您忘记了&

关于c - 检查 C 中数组的值时出现未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14693486/

相关文章:

java - 根据 String[] 创建 int[](特殊计数器)

c++ - ifstream 用于破坏散列字符串

haskell - 如何计算这个 Haskell 函数中发生了多少递归调用?

c - 在编程中增加一行的长度

c++ - 设置 opengl View 和投影转换

c - 如何摆脱C拼写检查程序中的标点符号?

将带有字符串数组作为参数的 glib C 方法转换为 Go

java - 用java读取后将excel中的数据存储在列表中

c++ - 如何在 C++ 中实现允许许多未定义数据类型参数的递归函数模板?

java - 如何通过回溯和递归来解决数独?