简体   繁体   English

我收到一个总线错误,并且代码在 3 次输入后自行停止工作

[英]i get a bus error and code stops working by itself after 3 inputs

I got 2 issues with this code?这段代码有 2 个问题? first is that it stops by itself after 3 different inputs of students and when i want the to print out all the students that passed it gives me zsh bus error?首先是它在 3 次不同的学生输入后自行停止,当我想打印出所有通过它的学生时,它给了我 zsh 总线错误? need help asap.尽快需要帮助。

zsh 总线错误

#include <stdio.h>  
#include <string.h>

struct student
{
    int no;
    char name[20];
    int studentnumber;
    int points;
    int b;
};

void passed(struct student st[], int b, int p)
{
    for (int j = 0; j < p; j++)
    {
        if (st[j].points >= b)
        {
            printf("%s passed\n", st[j].name);
        }
    }
}

int main()
{
    int i, b, e;
    int p = 1;

    struct student st[p];
    printf("insert data %d of participant:", p);

    for (i = 0; i < p; i++)
    {
        printf("\nName studentnumber points eingeben:");
        scanf("%s %d %d", st[i].name, &st[i].studentnumber, &st[i].points);

        printf("Would you like to instert another participant? 0 yds 1 no\n");
        scanf("%d", &e);
        if (e == 0)
        {
            p++;
            continue;
        }
        else
        {
            printf("Points to pass:");
            scanf("%d", &b);
            passed(st, b, p);
        }
    }
}
int p = 1;
struct student st[p];

This defines an array of p elements, using the value p has right then , which is 1. Later, when you increment p , the size of the array does not change .这定义了一个p元素的数组,使用值p具有right then ,即 1。稍后,当您增加p时,数组的大小不会改变 Thus, on the second and subsequent iterations of the loop, you write past the end of the array and the program malfunctions.因此,在循环的第二次和后续迭代中,您写入数组的末尾并且程序发生故障。

Dynamically resizable arrays have to be implemented by hand in C, using realloc .动态调整大小的 arrays 必须在 C 中使用realloc手动实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM