gem
gem

Reputation: 1

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

I got 2 issues with this code? 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?

zsh bus error

#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);
        }
    }
}

Upvotes: -1

Views: 291

Answers (1)

zwol
zwol

Reputation: 140846

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. 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.

Upvotes: 1

Related Questions