Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define NAME_LENGTH 100
- /* 2. Write a program to show the top students from a class given
- * their names and grades. The program should read the names of
- * the students and their grades from the keyboard. The program
- * will display a menu and allow the user to sort the students by
- * alphabetic order or by grades. For example the menu can look like
- * this:
- 0. Exit program
- 1. Give N, number of students
- 2. Enter the students
- 3. Display class in alphabetic order
- 4. Display class creating a top based on grades
- 5. Display the first 3 students according to their grades
- * but feel free to improve.
- */
- // Representation of table (first row represents the array index/position)
- // +-----------------+------------------------------------------+
- // | 0 | 1-99 |
- // +-----------------+------------------------------------------+
- // | grade (1 to 10) | String of name (including '\0') |
- // +-----------------+------------------------------------------+
- /* @table: table of students (array of strings)
- * @m: number of rows
- */
- void addStudent(char (*table)[100], unsigned *m) {
- char s[100];
- unsigned i = 0, j;
- table = realloc(table, sizeof(char[*m][NAME_LENGTH]));
- printf("Type the name of the student:\n");
- // read until newline ('\n')
- fgets(&table[*m - 1][1], 99, stdin);
- // remove the newline
- //table[*m - 1][strlen(table[*m - 1])] = '\0';
- printf("Type the grade of the student:\n");
- int grade;
- do {
- scanf("%d", &grade); // might improve later
- } while (grade > 10 || grade < 1);
- // placing the grade in the table
- table[*m - 1][0] = grade;
- // placing the name in the table
- //memcpy(&table[*m-1][1], s, strlen(s) + 1); // +1 for the terminating NULL character
- *m = *m+1;
- }
- int main() {
- unsigned size = 1;
- // allocating 1 byte because if size is 0, the return value depends on the particular library implementation (it may or may not be a null pointer)
- char (*students)[100] = malloc(1 * sizeof(char));
- addStudent(students, &size);
- printf("Name of first student:\n%c",(*(students+0)+1));
- //addStudent(students, &size);
- free(students);
- return 0;
- }
- //getdelim(char **lineptr, size_t *n, int delim, FILE *stream); (?): why does it take n as a pointer instead of simply n?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement