【发布时间】:2014-12-11 01:24:08
【问题描述】:
我正在尝试读取输入并将字符串存储在 char 数组中。但是,编译器会返回分段错误。此外,存储字符串不起作用并导致执行文件崩溃。 这是我的代码:
#include <stdlib.h>
#include <math.h>
/*scan functie*/
int inputProducts(int *resourceCost, int *profit, char **productName) {
int amount, i;
printf("number of products: \n");
scanf("%d", amount);
for (i = 0; i < amount; i++) {
printf("product: \n");
scanf("%s", productName[i]);
printf("resource cost for %s: \n", productName[i]);
scanf("%d", &resourceCost[i]);
printf("profit for %s: \n", productName[i]);
scanf("%d", &profit[i]);
}
return amount;
}
int main(int argc, char *argv[]) {
int amount;
int resourceCost[100],profit[100];
char *productName[100];
amount = inputProducts(resourceCost, profit, productName);
return 0;
}
【问题讨论】:
-
编译器不返回段错误。这是一个运行时错误。但是您几乎可以肯定超出了数组的大小,例如尝试使用
resourceCost[100],它只支持索引 0->99。 -
你最好检查
scanf的返回值always,因为当解析失败但你忽略错误时会发生“有趣”的事情。 -
amount 的取值也存在错误。我决定让程序打印它,当我输入 5 作为金额的值时,它会打印 2130567168....
标签: c arrays string char segmentation-fault