【问题标题】:storing Strings into Char array in C & segmentation fault在 C 和分段错误中将字符串存储到 Char 数组中
【发布时间】: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


【解决方案1】:
scanf("%d", &amount);   
for (i = 0; i < amount; i++)    {
     productName[i] = (char *)malloc(sizeof(char));
     printf("product: \n");     
     scanf("%s", productName[i]);

您没有为要存储在 productName 中的字符串分配任何空间。请尝试在您的 for 循环中添加这行代码。 它将为每个字符串在堆上腾出空间

productName[i] = (char *)malloc(sizeof(char));

【讨论】:

  • 我会尝试,但是,运行程序会导致它在键入并输入金额后崩溃......那里有什么问题吗?
  • **纠正了我的答案。我刚刚使用 malloc() 运行了您的程序并进行了更正,它运行良好。
  • 谢谢。它现在也适用于我。唯一的问题是我正在存储指针,因为我想存储实际值..
【解决方案2】:
 char *productName[100];

productName 是一个指针数组,它们未初始化为指向任何有效的内存位置。

scanf("%s", productName[i]);

在此处输入会导致您出现分段错误。

【讨论】:

  • 我该如何解决这个问题? char productname[100] 会起作用吗?
  • 提示:在输入之前将malloc返回的地址存储在每个索引处。
  • 感谢您的解决方案。我会试试这个。然而,这个练习的想法是存储一个字符串,而不是一个指针。但是当我在没有 * 的情况下初始化 char 数组时, inputProducts 行无法传递 char 数组(错误:不兼容的指针类型)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 2011-02-07
  • 2017-04-09
相关资源
最近更新 更多