Reputation: 13
I am trying to create a program that allows me to enter grades for a number of students (between 1-25). For each student, I am suppose to enter a number of grades (between 1-10). For each student I am supposed to supply their first and last name, age, and grade average depending on the number of grades I enter. This is for an assignment, so I am required to have a struct
in my program named Info
, and inside, it has the char
variables firstName and lastName, int
variable age, and float
variable average.
#include <stdio.h>
int gradeVar;
int studVar;
struct Info {
char firstName[20];
char lastName[20];
int age;
int Exam; //This is for something I planned to add later
float Average;
};
int main() {
printf("How many students will you grade (1-25)? ");
scanf("\n%i", &studVar);
if (studVar<1 || studVar>25) {
do{
printf("Invalid\n");
printf("How many students will you grade (1-25)? ");
scanf("\n%i", &studVar);
} while (studVar<1 || studVar>25);
}
printf("How many grades will you read per student (1-10)? ");
scanf("\n%i", &gradeVar);
if(gradeVar<1 || gradeVar>10) {
do{
printf("Invalid\n");
printf("How many grades will you read per student (1-10)? ");
scanf("\n%i", &gradeVar);
} while(gradeVar<1 || gradeVar>10);
}
struct Info Student[studVar];
for(int n=1; n <= studVar; ++n) {
printf("Enter First Name for student %i: ", n);
scanf("\n%s", Student[n].firstName);
printf("Enter Last Name for student %i: ", n);
scanf("\n%s", Student[n].lastName);
//Every thing worked fine until I added the last two lines below//
printf("Enter age for student %i: ", n);
scanf("\n%d", &Student[n].age);
};
return 0;
}
It is until I add the last two lines:
printf("Enter age for student %i: ", n);
scanf("\n%d", &Student[n].age);
That I got error in my output saying stacked smashing
I am not entirely sure why this is happening, and don't know where to fix it so that it runs the way I want it to. If you anyone can clarify this for me I'd appreciate it.
Upvotes: 1
Views: 1030
Reputation: 881113
In C, when you declare struct Info Student[studVar];
, the valid indexes for that array are zero through studVar - 1
, not 1 through studVar
.
Hence your scanf
statements inside the loop should be using n - 1
rather than n
. Your problems is that, when you enter 2
for the number of students, that gives you Student[0]
and Student[1]
.
Trying to write to Student[2].id
is going to result in undefined behaviour such as, hmmm, ..., stack smashing I guess :-)
Upvotes: 3
Reputation: 43188
Expected:
for(int n=0; n < studVar; ++n)
Got:
for(int n=1; n <= studVar; ++n)
Arrays are 0 based not 1 based.
There's another overflow waiting for you if you exceed 19 characters in a name component.
Upvotes: 2