简体   繁体   中英

How to pass each element of array of structs into a function?

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.

When passing a struct to a function, the function actually copies the struct to the input struct parameter and works on it. So the function addStudent did not work on your global array item but on a local copy.

You should pass a pointer to the struct item to the function and work on that. The code then looks like this:

int addStudent(struct students *st,char sname[], int marks){
    static int count = 0;
    strncpy(st->name,sname,strlen(sname)+1);
    st->marks = marks;
    count++;
    return count;
}

and the call to the function addStudent looks like this:

    size = addStudent(&st[i], name, marks);

In general the code can have other improvements like not using global variables, and static counters, but this is outside the scope of your question.

there is another issue here, using strncpy for copying strlen of string, does not end the string with null. So you should use strlen+1 to copy also the null termination, or simply use snprintf which adds null termination at end of string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM