The structure members fname
and lname
are pointers to characters, not character arrays. Therefore, the scanf
call
scanf("%s %s %f", &(ptr+i)->fname, &(ptr+i)->lname, &(ptr+i)->score);
is wrong and invokes undefined behaviour. You need to make those members as arrays.
#define MAX_LEN 40
struct student
{
char fname[MAX_LEN];
char lname[MAX_LEN];
float score;
};
Also, when you pass an array to a function, it decays into a pointer to its first element. You should not use the address of
operator &
on it. Do not cast the result of malloc
. Why do you allocate memory in the printStudents
function? It causes memory leak as you don't free it. Also, the function parameter s
does not need to be struct student **
type. I suggest the following changes -
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 40
struct student
{
char fname[MAX_LEN];
char lname[MAX_LEN];
float score;
};
void printStudents(struct student *s, int student_size);
int main(void)
{
int base_number, i;
int students;
struct student *ptr;
printf("Enter Number of Students:\n");
scanf("%d", &base_number);
ptr = malloc(base_number * sizeof *ptr);
students = base_number;
printf("\nEnter Student Information\nExample: John Smith 98.50\n\n");
for(i = 0; i < base_number; i++)
{
printf("Student %d:\n", i+1);
scanf("%s%s%f", (ptr+i)->fname, (ptr+i)->lname, (ptr+i)->score);
}
printStudents(ptr, students);
free(ptr);
return 0;
}
void printStudents(struct student *s, int student_size)
{
int i;
for(i = 0; i < student_size; i++)
printf("%s %s %.2f\n",
(s+i)->fname,
(s+i)->lname,
(s+i)->score);
}