harshvardhan.agr
harshvardhan.agr

Reputation: 175

Malloc for structures

I am not getting the correct output here, The code takes the no of inputs and option as an input, then takes the name of student year and gender and based on option provided gives the output. The output can be the name appearing first in the dictionary or the smaller value of the year amongst the inputs.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student_record
{
    int passing_year;
    char gender;
    char name[20];
};

typedef struct student_record student;

student* find_specific(student* find, int option_num, int number)
{
    int i;
    student* temp = find;
    int opt = option_num;
    int num = number;

    if(opt==1)
    {
        for(i=0; i<num; i++)
        {
            if( strcmp(temp->name, find[i].name) >0)
                temp = find+i;
        }
    }
    else
    {
        for(i=0; i<num; i++)
                {
                    if (temp->passing_year > find[i].passing_year)
                        temp = find+i;
                }
    }

    return temp;

}

int main() {

    student* example;
    student* final;

    int i;
    int option_num, number_of_students;
    printf("Enter 2the number of students, option number");
    scanf("%d" "%d", &number_of_students, &option_num);

    example = (student* )malloc(number_of_students * sizeof(student));

    printf("Enter the name, passing year and gender");
    for(i=0; i< number_of_students; i++)
    {

        scanf("%s" "%d" "%c", example[i].name, &example[i].passing_year, &example[i].gender);
    }

    final = find_specific(example, option_num, number_of_students);

    printf("%s" "%d" "%c", final->name, final->passing_year, final->gender );





    return 0;
}

i am getting a segmentation fault. I can't figure out exactly where am I screwing up.

Upvotes: 0

Views: 76

Answers (1)

Jim Lewis
Jim Lewis

Reputation: 45025

Your scanf() and printf() format strings are probably wrong.

scanf("%s" "%d" "%c", example[i].name, &example[i].passing_year, &example[i].gender);

should probably be

scanf("%s %d %c", example[i].name, &example[i].passing_year, &example[i].gender);

(without the extra quotes). The compiler will concatenate adjacent string literals, so instead of a compiler error, it interpreted your format string as equivalent to "%s%d%c" (without whitespace in between). That probably doesn't match the layout of your input, so some of the values were probably left uninitialized in a way that caused problems later.

You should always check the return value of scanf and similar library functions, to ensure that you got the input format you told the compiler to expect.

Upvotes: 3

Related Questions