Why does not it overwrite data while inputting data in for Loop (Structure)?

61 Views Asked by At

I'm a beginner in c I've been working on a program in C where using structure which represents students, and variable of structure contains the student's marks. My goal is to input marks for 2 students for 3 subjects each.

#include <stdio.h>

// Defining a structure for student details
struct Student {
    int mark;
};

int main() {
    struct Student st[2];

    // Input details for 2 student marks
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; j++) {
            printf("Marks: ");
            scanf("%f", &st[j].mark);
        }
    }

    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; j++) {
            printf("Marks: ", st[j].marks);
        }
    }

    return 0;
}

But had a confusion while writing it, As we're asking for 3 subjects for 2 students meaning students marks should run for 6 times in total. Won't it overwrite the Data ? Like

Marks: 5 Marks: 7 Marks: 8

Here, won't it overwrite the last data to the variable since we've not declared the array to store for 6 subjects,int mark[Num_of_subj]. In this case that should be 8 despite user entering 5 as the 1st Marks ?.

1

There are 1 best solutions below

8
seb On

To answer your primary question, the code you provided will put the first grade entered in the first student mark, the second grade entered in the second student mark and the last grade entered will cause undefined behavior; Thus it can overwrite data, but won't necessarily.

To correct this issue, you can make the Student struct have a list attribute, and since you are inputing floats, it should be a list of floats. Then, you also need to correct the indices used in the first for loop since, as explained above, they do not perform the intended behavior.

Something like this should work :

#include <stdio.h>
#define NUM_SUBJECTS 3
// Defining a structure for student details
struct Student {
    float marks[NUM_SUBJECTS];
};

int main() {
    struct Student st[2];

    // Input details for 2 student marks
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < NUM_SUBJECTS; j++) {
            printf("Marks: ");
            scanf("%f", &st[i].marks[j]);
        }
    }

    for (int i = 0; i < 2; ++i) {
        printf("Marks for student %d:\n", i + 1);
        for (int j = 0; j < NUM_SUBJECTS; j++) {
            printf("Subject %d: %f\n", j + 1, st[i].marks[j]);
        }
    }

    return 0;
}


Here the define is a C macro which allows you to change the number of subject at only one place.