首页 > 解决方案 > “数组”函数正在阻止程序正常运行

问题描述

我的功能无法正常工作。程序运行,但是当它进入 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;

                }
}

预期成绩:

实际结果:

标签: carraysfunctionpointers

解决方案


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


推荐阅读