I have little programming experience and have had some issues regarding trying to get said structure to be read as an array.
The code that I have been working on does not seem to output anything at the moment. I want to eventually be able to sort the array, but first I need to actually get an array going.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Students {
char name[20];
char surname[20];
int id;
float lab;
float kd;
};
void printStudent(struct Students *st );
float student(struct Students *st);
int main() {
float student(struct Students *st){
struct Students stud[4];
strcpy(stud[0].name, "John");
strcpy(stud[0].surname, "Doe");
stud[0].id = 456;
stud[0].lab = 7.31;
stud[0].kd = 8.55;
strcpy(stud[1].name, "Tom");
strcpy(stud[1].surname, "K");
stud[1].id = 001;
stud[1].lab = 9.25;
stud[1].kd = 8.93;
strcpy(stud[2].name, "Jane");
strcpy(stud[2].surname, "Dee");
stud[2].id = 201;
stud[2].lab = 7.31;
stud[2].kd = 6.55;
strcpy(stud[3].name, "Alice");
strcpy(stud[3].surname, "Lee");
stud[3].id = 199;
stud[3].lab = 8.95;
stud[3].kd = 9.22;
strcpy(stud[4].name, "Victor");
strcpy(stud[4].surname, "Mann");
stud[4].id = 167;
stud[4].lab = 10.00;
stud[4].kd = 9.50;
printStudent(&st[0]);
printStudent(&st[1]);
printStudent(&st[2]);
printStudent(&st[3]);
printStudent(&st[4]);
return 0;
}
void printStudent(struct Students *st){
printf("%s \n", st->name);
printf("%s \n", st->surname);
printf("%d \n", st->id);
printf("%.2f \n", st->lab);
printf("%.2f \n", st->kd);
}
}
CodePudding user response:
You want this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Students {
char name[20];
char surname[20];
int id;
float lab;
float kd;
};
void printStudent(struct Students* st);
float student(struct Students* st);
void printStudent(struct Students* st) {
printf("%s \n", st->name);
printf("%s \n", st->surname);
printf("%d \n", st->id);
printf("%.2f \n", st->lab);
printf("%.2f \n", st->kd);
}
int main() {
struct Students stud[5]; // you need 5 students (0, 1, 2, 3, 4) that's 5
// fill students 0 to 4
strcpy(stud[0].name, "John");
strcpy(stud[0].surname, "Doe");
stud[0].id = 456;
stud[0].lab = 7.31;
stud[0].kd = 8.55;
strcpy(stud[1].name, "Tom");
strcpy(stud[1].surname, "K");
stud[1].id = 001;
stud[1].lab = 9.25;
stud[1].kd = 8.93;
strcpy(stud[2].name, "Jane");
strcpy(stud[2].surname, "Dee");
stud[2].id = 201;
stud[2].lab = 7.31;
stud[2].kd = 6.55;
strcpy(stud[3].name, "Alice");
strcpy(stud[3].surname, "Lee");
stud[3].id = 199;
stud[3].lab = 8.95;
stud[3].kd = 9.22;
strcpy(stud[4].name, "Victor");
strcpy(stud[4].surname, "Mann");
stud[4].id = 167;
stud[4].lab = 10.00;
stud[4].kd = 9.50;
// print students 0 to 4
printStudent(&stud[0]);
printStudent(&stud[1]);
printStudent(&stud[2]);
printStudent(&stud[3]);
printStudent(&stud[4]);
return 0;
}
There is not much to comment, it's pretty autodocumented.