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 ?.
stis an array of length 2 but you are accessing is withst[2]at some point, which will cause a buffer overflow. If I understood correctly, the line you want isscanf("%f", &st[i].mark[j]);, and definemarkto be an arrayStudentstruct does not have themarksmember you are shown accessing in the second set of loops.