c - 在 C 中将字符串存储到 Char 数组中 & 段错误

标签 c arrays string char segmentation-fault

我正在尝试读取输入并将字符串存储在字符数组中。但是,编译器会返回段错误。另外,存储字符串不起作用并导致执行文件崩溃。 这是我的代码:

#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/

相关文章:

python - 在 2 个单独的 numpy 数组中查找匹配点

c++ - 与非指针相比,char 指针初始化?会发生什么

c - winsock编译错误

C - 在数组中使用 malloc() 存储指针,之后不能释放它们

perl - Tie::File 是否延迟加载文件?

string - 在 CMake 中如何将命令的多行输出转换为列表?

string - 按分隔符拆分字符串并包含分隔符 - Common Lisp

string - 如何在 Netezza 中替换完整子字符串

CS50 Mario(更舒适)错误消息

c - printf 如何返回成功打印的字符数?