0

I am getting segmentation error?? PLS HElP

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

void display(char n2[], int x2[], char c1[], int p);

void display(char n2[], int x2[], char c1[], int p)
{
  printf("Student Name :  %s \n", n2[p]);
  printf("Student Roll No : %d \n", x2[p]);
  printf("Student Class : %s \n ", c1[p]);
}

int main()
{
  char n[50], c[5], n1;
  int y, x[8], x1;
  int p1 = 0;

  printf("Enter the number of students: \n");
  scanf("%d", &y);

  fflush(stdin);

  for (int i = 0; i < y; i++)
  {
    fflush(stdin);
    printf("Enter the Student Name : \n");
    scanf("%s", n[i]);
    fflush(stdin);
    printf("Enter the Student Class : \n");
    scanf(" %s", c[i]);
    fflush(stdin);
    printf("Enter the Student Roll No : \n");
    scanf(" %d", &x[i]);
    fflush(stdin);

  }
  fflush(stdin);

  printf("Enter the Student Name and Roll Number :\n");

  scanf("%s %d", &n1, &x1);

  for (int i = 0; i < y; i++)
  {
    if ((n[i] == n1) && (x[i] == x1))
    {
      p1 = i;
    }
    else
    {
      printf("No Such Entry!!");
    }
  }

  display(n, x, c, p1);
  return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 2
    `char n[50]` declares one string of length 50. You need `MAX` strings of length 50, where `MAX` is the maximum number of students you want to handle and provided the maximum length of a student name is 50. I also suggest you use meaningful variable names., e.g. `NbStudents`instead of `y`, etc. You also should read (again?) the chapter dealing with strings in your learning material and read [this](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c) for comparing strings. – Jabberwocky Oct 15 '21 at 08:46
  • BTW for this kind of problems you should use an array of `struct`s, this will make your code much simpler. That's a typical use case for `struct`s. I'm even pretty sure that this is an exercise where you are supposed to use `struct`s. – Jabberwocky Oct 15 '21 at 08:57
  • [Look here](https://godbolt.org/z/7Wx1rPnqf), then [read this](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) to avoid wasting a lot of time. – n. m. could be an AI Oct 15 '21 at 09:50

1 Answers1

0

The error occurs here:

scanf("%s",c[i]);

You are trying to store a string into a char (n[i]). You should define n and the others as an array of strings instead of a string, for example:

char n[50][ 50 ], c[50][50], n1[50];

Also, you can't compare strings like you do on this line:

if ((n[i]== n1) && (x[i] == x1))

Use strcmp instead to compare strings.