c - 将用户输入存储到两个数组时中止陷阱

标签 c arrays scanf abort

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

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

我还在 scanf 中的数组前面添加了&符号,我发现这样做很奇怪,但代码无法编译。

包括

int main(空){

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]);

}

}

最佳答案

我认为你的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 这样的调试器将帮助您查明代码中发生错误的位置。并且可能会帮助您找出错误。

关于c - 将用户输入存储到两个数组时中止陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50478573/

相关文章:

c - 数组中的唯一数字

c++ - 两个 std::arrays 的交叉部分

c++ - 删除动态分配的数组时出错

c - 在输出平均数时,程序呈现段错误 11

c - 我想使用一个开关盒而不是两个开关盒

C++ 获取不同线程的回溯

python 切片多维数组

c - while 循环中的 scanf 仅适用于第一次迭代

c - 如何在c中检查scanf两个整数

c++ - 使用 C++ 连接到 mysql