I am learning structs
and I am still little confused about them and what they do. The code I have is my attempt of it and I keep getting segmentation faults. My goal for the main is to ask the user to see how many students they want to add, and each information for name and score while calling a function. I also want to print the data array off to the user.
For the
loadStudentData()
function, I want to store thenewName
andNewScore
into thenewStudent
Structure.For
printStudentData()
I want to print data for a single studentThen for the
printStudentArray()
I want to callprintStudentData()
function on each member for the students array.
My code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STUDENT_NAME_LENGTH 20
typedef struct{
char* name;
int score;
}Student;
void loadStudentData(Student *newStudent,char* newName,int newScore);
int printStudentData(Student student);
void printStudentArray(Student* students, int numStudents);
/*
*
*/
int main(int argc, char** argv) {
int numberOfStudents;
Student *newStudent;
char* newName;
int newScore;
int student;
Student students[numberOfStudents];
printf("how many students: ");
scanf("%d", &numberOfStudents);
loadStudentData(newStudent, newName, newScore);
printStudentArray(students, numberOfStudents);
return (EXIT_SUCCESS);
}
void loadStudentData( Student *newStudent, char* newName, int newScore){
int i;
char *studentName = (char *) malloc(STUDENT_NAME_LENGTH * sizeof(char));
scanf("%s", studentName);
newStudent->name = studentName;
int nScore;
scanf("%d", &nScore);
newStudent[i].score = newScore;
}
int printStudentData(Student student){
int i;
printf("Student name\t%s\n",) ;
printf("Student score\t%d\n",);
}
void printStudentArray(Student* students, int numStudents){
int i;
for (i = 0; i < numStudents; i++) {
printf("Student name\t%s\n", students[i].name);
printf("Student score\t%d\n", students[i].score);
}
}