为什么我不能在C中使用一维数组中的输入值

  • 本文关键字:一维数组 不能 c arrays
  • 更新时间 :
  • 英文 :


我知道:我可以使用二维数组来存放许多字符串。但是,我想用一维解决此问题;因此,请不要建议我使用二维用于求解的数组。


我有一个小的一维数组,该数组用于存储许多字符串。这是所有源代码:

#include <stdio.h>
void main()
{
    #define MAX 10
    int N = 3;
    char * str[MAX];
    printf("Input a string in each line:nn");
    for (int i = 0; i < N; i++)
    {
        printf("str[%d] = ", i);
         gets(str[i]);
    }
    printf("nn---nnExport the list of strings:nn");
    for (int j = 0; j < N; j++)
    {
        printf("str[%d] = ", j);
        printf("%sn", str[j]);
    }
}

编译时,编译器不会返回任何错误或警告。但是,在输入数据后,Windows有一条错误消息:

问题导致该程序停止正确工作

然后,我的程序被打破了。

在此数组中: char * str[MAX]

没有任何条目初始化以指向有效(正确分配的)内存块。

,因此您不应scanf("%s", &str[i]),直到您有初始化的条目#i

char * str[MAX];

str是指针的数组。您应该在编写任何内容之前将内存分配给指针。

str[i] = malloc(20);/* Showing an example of using malloc() . How much memory should be allocated is left to you */

使用scanf()扫描字符串不是一个好主意,我宁愿 fgets()

最新更新