I am trying to complete some coursework, our exercise is focused around using data structures. I am trying to write a new method to print out each element in the array I have created but my for loop is not recognising the existence of the array that has been created above it. It is giving me an error at the 'students.Length' part.
I'm sorry if this is a really stupid question because I feel like there's a very simple answer to this but I just can't understand why it's telling me the 'students' array doesn't exist?
public struct student_data
{
public string forename;
public string surname;
public int id_number;
public float averageGrade;
}
static void populateStruct(out student_data student, string fname, string surname, int id_number)
{
student.forename = fname;
student.surname = surname;
student.id_number = id_number;
student.averageGrade = 0.0F;
}
public static void Main(string[] args)
{
student_data[] students = new student_data[4];
populateStruct(out students[0], "Mark", "Anderson", 1);
populateStruct(out students[1], "Max", "Fisher", 2);
populateStruct(out students[2], "Tom", "Jones", 3);
populateStruct(out students[3], "Ewan", "Evans", 4);
}
static void printAllStudent(student_data student)
{
for(int i = 0; i < students.Length; i )
}
CodePudding user response:
In printAllStudent
, you are trying to retrieve the length of a variable named students
. This is not the same variable you have received, which is named student
. As a result, students
is undefined in the body of printAllStudent
.
CodePudding user response:
The printAllStudent
method is currently taking in a single student_data
struct as an argument rather than a student_data[]
array. Additionally, you're trying to access the students
array that was defined inside another method, which is not accessible. Instead, you should use the array that's passed into the method:
static void printAllStudent(student_data[] input)
{
for (int i = 0; i < input.Length; i )
{
Console.WriteLine(input[i]);
}
}
Also, to make the output more useful, it might be a good idea to override the ToString
method on your student_data
struct so that it outputs some information about the student. For example:
public struct student_data
{
public string forename;
public string surname;
public int id_number;
public float averageGrade;
public override string ToString()
{
return $"{id_number}: {forename} {surname} (avg grade: {averageGrade})";
}
}