[英]Get exception error in C when trying to loop array
//Program Written By: Andre Chitsaz-zadeh
//Program Written On: 10/7/12
//Program calculates book cost for multiple book orders. Program written using multiple functions.`
#include <stdio.h>
#define SIZE 5
void inputData();
int main ()
{
inputData();
}
void inputData()
{
int i = 0;
int costs[5];
printf( "\nPlease enter five products costs.\n" );
while(i < 5)
{
scanf("%d", costs[i]);
i = i + 1;
}
}
为什么会出现异常错误? 该程序看起来很简单! 它可以毫无问题地进行编译,但是一旦我输入一个数字,它就会说“该程序已停止工作”。 谢谢!!
scanf("%d", costs[i]);
应该:
scanf("%d", &costs[i]);// &cost[i] gets the address of the memory location you want to fill.
它应该是
while(i < 5) {
scanf("%d", &costs[i]);
i = i + 1;
}
我假设有一点错字,无论如何,您都需要提供要将整数扫描到的数组元素的地址。
我想这是这行:
scanf("%d", costs[i]);
它应该是:
scanf("%d", &costs[i]);
scanf
需要一个指向应该将读取结果放入其中的变量的指针。
这看起来像一个作业问题,通过对该程序的注释来判断它是否具有多种功能。 如果函数是新函数,则指针可能尚未涵盖。 在这种情况下,我的解释如下:
scanf
在将读取结果放入其中的变量之前需要&
。 您将在几周后了解原因。
我认为您需要将scanf
行更改为
scanf("%d", &costs[i]);
您需要传递int的地址以将用户输入写入其中。 您当前的代码传递了costs[i]
的价值。 这是未定义的,因此将指向内存中不可预测且可能不可写入的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.