我正在尝试读取输入并将字符串存储在字符数组中。但是,编译器会返回段错误。另外,存储字符串不起作用并导致执行文件崩溃。 这是我的代码:
#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;
}
最佳答案
char *productName[100];
productName
是一个指针数组,它们未初始化为指向任何有效的内存位置。
scanf("%s", productName[i]);
在这里获取输入会导致段错误。
关于c - 在 C 中将字符串存储到 Char 数组中 & 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26391498/