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

Time:02-01

#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

CodePudding user response:

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. "3s"

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);

CodePudding user response:

#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);
        printf("Your Sction = ");
        scanf("%c", &student[i].section);

    }
    return 0;
}

Does anyone fix this problem when I run this code its take two input but the last input is skipped why ??? please help me to fix this problem.

please check this image Image

  •  Tags:  
  • Related