【问题标题】:Abort trap when storing users input into two arrays将用户输入存储到两个数组时中止陷阱
【发布时间】:2018-11-01 20:45:30
【问题描述】:

我将接收用户输入,其中包含他们的身份和标记,用空格分隔。代码编译,我可以在提示符处输入答案,但是,在提示符结束时(第一个循环结束),出现“中止陷阱:6”。

如果您能帮助我找出出现此评论的原因,我将不胜感激。我读到它可能是我覆盖了其他内存,但看起来我的循环并没有超出我希望它们循环的范围(用户给了我 10 个答案)。

我还在 scanf 的数组前面添加了 & 符号,我觉得这样做很奇怪,但是代码没有编译通过。

包括

int main (void){

char id[10];

int mark[10];

for (int i=0;i<10;i++){


    printf("Enter ID and mark: \n");



    scanf(" %s %d", &id[i], &mark[i]);
}
for (int i=0;i<10;i++){

    printf("%c ",id[i]);

}

}

【问题讨论】:

  • 附言。我还在第一个循环中的 printf 之后使用了“gets”,使用一个数组来包含 id 和 mark,但是,这也导致了相同的“Abort error: 6”。
  • 您扫描的字符串是否仅使用 1 个字符?为什么不在 scanf 中使用 %c
  • 很抱歉没有解决这个问题。
  • 我收到的ID会是:j134432(一个字母,后跟6个数字)
  • 但您将其存储到一个字符中?

标签: c arrays scanf abort


【解决方案1】:

我认为您的 ID 读取错误,您的 ID 是 7 个字符长度的字符串,而您的 char id[10] 是一个 10 字符的字符串(您打算在其中使用字符串列表),您应该改用 char *ids[10]

char *ids[10] = { NULL }; // list of 10 string, initialized to NULL
int mark[10];
for (int i=0;i<10;i++){
    ...
    char* id=malloc(8*sizeof(char)); // allocate a new string to store
    scanf( "%7s %d\n", id, &mark[i] ); // check the result of the scanf to ensure you got the correct input
    ids[i] = id; // store the string at position in the list
}
for (int i=0;i<10;i++){
     printf("%s\n", ids[i]);
}

还可以使用像GDB 这样的调试器来帮助您查明代码中发生的错误。并且可能会帮助您找出错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多