“数组”功能阻止程序正常运行

时间:2019-04-12 01:20:57

标签: c arrays function pointers

我的功能无法正常工作。该程序可以运行,但是当它进入for循环时,该功能将无法运行并停止该程序,即使该程序应该继续循环也是如此。如果可以的话,请检查我的Array函数,并告诉我是否有我不了解或无法正确执行的操作。

感谢您的时间。

我知道事实上循环不是问题,因为当我删除函数时,它可以正常工作。我还尝试将“ b”放置在函数数组参数中,例如“ int Array(int a [b],int b,int c);”

#include <stdio.h>
#include <stdlib.h>

/*Function*/

int Array(int a[], int b,  int c);

/*Main Program*/
int main()

{

int S, C, *A, *B;
printf("How Many Numbers Would You Like in Array A and B? ");
scanf("%d\n", & S);

/*For Loop Asking The User to Enter a Value and using the Array function to calculate/store the B[] Value*/
for (C=0; C<=S; ++C){
    printf("\nWhat is A[%d]  ", C);
    scanf("%d", & A[C]);
    B[C] = Array(A, S, C);
    }
}


/*Function*/    
int Array(int a[], int b, int c)
{
if (a[c] < 0){
        return a[c] * 10;

    } else {
        return a[c] * 2;

                }
}

预期结果:

  • 程序要求用户输入将用于* A和* B的数组大小

  • 程序使用for循环要求用户输入数组* A中每个位置的值,并使用该值计算每个匹配的B位置的值

实际结果:

  • 程序要求用户输入将用于* A和* B的数组大小

  • 程序使用for循环要求用户输入数组* A中每个位置的值,程序要求用户输入一个值,然后停止运行。

1 个答案:

答案 0 :(得分:1)

您没有为数组A分配任何内存。您只是将其声明为指向int的指针,然后开始向其中写入值,这些值将进入某个随机内存位置。在获取到S的第一个scanf之后,需要分配A = malloc(S * sizeof(int))才能访问它。