Search code examples
carraysrecord

How to store a record in an array?


Here is what i am trying to do. I am getting 3 user inputs from the user(name, age and gender) and all these inputs are one record. For example name=John, age= 15, gender= M , this is the record of the person named John.

I am trying to make 5 records like the example above and i am trying to store it to an array. The problem is i am not aware of how to do it.

Here is what i have done so far :

#include<stdio.h>
#include<conio.h>
#define Max 40


struct person{

    char name[Max];
    int age;
    char gender;

};

void inputdetails(struct person *,struct person []);

main()
{

struct person students[5]; //created an array type person to store the records

    struct person k;
    inputdetails(&k,students); //passed the array in to the input details function

}

void inputdetails(struct person *q,struct person hello[])
{
    int i=0;

    for(;i<5;i++)
    {
    printf("Enter name\n");
        gets(q->name);

    printf("Enter age\n");
    scanf("%d",&(q->age));

        fflush(stdin);
    printf("Enter gender\n");
    scanf("%c",&(q->gender));  


}

}

How do i do this ? How can i store 1 whole record in to the array,so when i make a function to display the records , i can just give an index number so it will display the record stored in that index?

Thank you for your time.


Solution

  • Move the for loop into main, like this:

    int main() {
        struct person students[5]; //created an array type person to store the records
        for (int i = 0 ; i != 5 ; i++) {
            inputdetails(&students[i], i);
        }
        return 0;
    }
    void inputdetails(struct person *q, int pos) {
        // Put all the data into q->...
        printf("Enter name of student %d\n", pos);
        // Do not use gets(), it's a security hazard
        scanf("%39s", q->name);
        ...
    }
    

    Your current implementation creates an unnecessary struct person k, and runs the loop inside the inputdetails function. An assumption is made that the second argument points to an array of size five. Finally, inside the loop you keep re-assigning the elements of the same temporary struct (which points to k inside main(), which is why the students does not get filled.

    I changed inputdetails to read a single entry at a time. Now main() is in charge of where the data is placed: it passes a pointer to each element of students[] in turn, along with the sequence number of the student for printing purposes.