- #include <stdio.h>
-
-
typedef struct
-
{
-
char name[20];
-
double gpa;
-
}student;
-
-
void fill_up( int *stud_num, student *stud_arr);
-
void display(student stud_arr[]);
-
-
student *stud_arr;
-
int *stud_num;
-
void main()
-
{
-
int stud_num;
-
fill_up(&stud_num, stud_arr);
-
display(stud_arr);
-
while(1);
-
}
-
-
void fill_up(int *stud_num, student *stud_arr)
-
{
-
int i;
-
printf("How many student --> "); scanf("%d", &stud_num);
-
stud_arr = (student *)calloc(*stud_num, sizeof(student));
-
for(i = 1; i <= *stud_num; i++)
-
{
-
printf("student %d --> ", i); scanf("%s", stud_arr[i].name);
-
printf("gpa --> "); scanf("%lf", &stud_arr[i].gpa);
-
}
-
}
-
-
void display(student *stud_arr)
-
{
-
int j;
-
for(j = 1; j <= *stud_num; j++)
-
{
-
printf("student %d --> %s", j, stud_arr[j].name);
-
printf("gpa --> %.2f\n\n", stud_arr[j].gpa);
-
}
-
}
How about this:
1) You declare int *stud_num as a global variable, but then redefine it in your main function. I think you should get rid of the global variables, as you pass variables to each method that needs them.
2) When calling fill_up, you pass stud_num's address, and it is held in a temporary pointer value. This is OK, but then you use scanf to input into the address of the pointer. Shouldn't you write "scanf("%d", stud_num);" so that data is written to the value held in the stud_num pointer i.e. the integer variable declared in main()?
3) Also in fill_up, you have a for...loop running from 1 to <= *stud_num, then use it to set values of your array from 1, 2, 3...*stud_num. But indexing starts at 0, and you will be writing to an out-of-bounds area at stud_arr[*stud_num], so your loop should be from 0 to < *stud_num.
4) The same mistake as (3) occurs in display() - you will be trying to write data at an out-of-bounds place.
Finally, while your while(1); loop will create the 'hanging' effect you desire, it also makes closing the program a hassle, and closing it with some sort of shortcut (not sure if you're using Windows, so I can't say using the X button) will probably create some slight errors - not completely sure what, but if a program doesn't close successfully, it may create a problem in the processor.
I suggest displaying a simple message (such as "Press any key and enter to continue"), and then using scanf to input into a temporary variable. This will stop the program from flashing off the screen, but you will still be able to enter that value and end the program as it was meant to end.