c - “数组”函数正在阻止程序正常运行
问题描述
我的功能无法正常工作。程序运行,但是当它进入 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 中的每个位置输入一个值,程序要求用户输入一个值然后停止运行。
解决方案
您没有为数组 A 分配任何内存。您只需将其声明为指向 int 的指针,然后开始向其写入值,这些值将转到某个随机内存位置。在第一个获得 S 的 scanf 之后,您需要A = malloc(S * sizeof(int))
在访问它之前进行分配。
推荐阅读
- reactjs - 从 iframe 更新本地存储后强制重新渲染组件
- jquery-scrollify - 我的页面偶尔会卡在滚动的中间
- mongodb - 使用 Spring Boot 的 MongoDB 聚合管道
- sockets - 来自广播节点的 UDP 冲突是否可能?
- python - 在 Tornado 中关闭 cookie
- php - 处理 php : Scanimage -L (usb)
- python-3.x - 气流记录 BrokenPipeException
- javascript - FlatList renderItem 被多次调用
- java - 一台计算机损坏 Excel 文件(通过我的程序通过 Apache POI 创建),而其他计算机工作正常
- android - 如何使用 sqlite 数据设置多个警报?