Search code examples
cstructure

I face a problem in C. Input is wrong-- its say Segmentation fault


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

struct student_details{
    char name[34];
    int roll;
    char section;
};

int main(){
    struct student_details student[5];

    for (int i = 0; i < 5; i++)
    {
        printf("Your full name = ");
        scanf("%s", student[i].name);
        printf("Your roll = ");
        scanf("%d", student[i].roll);

    }
    return 0;
}

I think something is wrong with my code anyone please fix this. When I run this code, it's Shows an error. after running this code this code take 1 time input and second input is skipped.

Check this Image


Solution

  • The scanf function expects to accept a format string and then pointers to the data you want to scan into. student[i].name is an array, which in this case decays into a pointer to its first element. This works.

    Note: This array only contains 34 characters. With the null terminator, you want to use a width specifier with scanf to limit the input and prevent a buffer overflow. "%33s"

    When you try to read the roll:

    scanf("%d", student[i].roll);
    

    student[i].roll is an int, not a pointer. But pointers are numbers, so this will compile. Your compiler should warn you about it, though. But, then the program tries to dereference this value it thinks is a pointer, and a segmentation fault occurs.

    What you want to do is pass the address of student[i].roll.

    scanf("%d", &student[i].roll);