I am trying to create a simple c program having an array of structures and I am passing each element of the array into a function and then trying to display it below is my code.
#include<stdio.h>
#include<string.h>
struct students{
char name[50];
int marks;
}st[10];
int size;
int addStudent(struct students st,char sname[], int marks){
static int count = 0;
strncpy(st.name,sname,strlen(sname));
st.marks = marks;
count++;
return count;
}
void showStudents(int size){
int i;
printf("Total number of students : %d\n",size);
for(i=0;i<size;i++){
printf("Student Name : %s\nMarks : %d\n",st[i].name,st[i].marks);
}
}
int main(){
int n, marks, i;
char name[50];
printf("Enter the total number of students : ");
scanf("%d",&n);
getchar();
for(i=0;i<n;i++){
printf("Enter the name of the Student : ");
fgets(name,50,stdin);
printf("Enter the marks of the student : ");
scanf("%d",&marks);
getchar();
size = addStudent(st[i], name, marks);
}
showStudents(size);
return 0;
}
and I am getting the following output
Enter the total number of students : 2
Enter the name of the Student : shibli
Enter the marks of the student : 23
Enter the name of the Student : max
Enter the marks of the student : 45
Total number of students : 2
Student Name :
Marks : 0
Student Name :
Marks : 0
Instead of getting the names and the marks I am getting no values can anyone help me what I am doing wrong with my code.
f(x)can't changex.starray -as a pointer argument- to yourshowStudentsfunction. In C, every argument is passed by value.sttoshowStudents. You are using it as a global variable, and that is bad style. Declarevoid showStudents(struct students*st, size_t nbst);st[i]is a struct, not an address, asstis an array of structures.