Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char **students; /* one is the array of pointers to char to store students’ names */
int * scores; /* an array of integers to store the results */
int num, i;
if ( argc > 1 ) {
num = atoi( argv[1] );
} else {
printf("Please enter a number of students.\n");
exit(0);
}
if ( num <= 0 )
{
printf("Please enter a number of students.\n");
exit(0);
}
students = malloc( num * sizeof *students );
scores = malloc( num * sizeof *scores );
for ( i = 0; i < num; i++ )
{
char buff[BUFSIZ];
printf("Enter the student's name: ");
fgets( buff, BUFSIZ, stdin ); /* NEVER use gets */
students[i] = malloc ( strlen(buff) + 1 );
strcpy( students[i], buff );
printf("Enter this student's score: ");
fgets( buff, BUFSIZ, stdin );
sscanf( buff, "%d", &scores[i] );
}
for ( i = 0 ; i < num ; i++ ) {
free( students[i] );
}
free(students);
free(scores);
return 0;
}
And read the FAQ on
- casting malloc
- using gets
- using fflush(stdin)