Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in strcmp() when I use a structure as a parameter

My program needs these functionalities:

NOTE: I did not include the codes for the numbers 1,2 & 4 since I already finished them. The 3rd one is my problem.

  1. The program should continuously allow input from the user as long the user still wants to. (Dynamically)
  2. Get the final grade of a student (average of frst_grade, scnd_grade, fnl_grade)
  3. Get the number of students per college.
  4. Get student name by inputting s_id.

My problem is how to compare the search input to the user input in s_college to get the number of students. The only way I know is by using strcmp() but it gives me this error: invalid conversion from 'char' to 'const char*' [-fpermissive]

So how do I compare these two to get the number of students per college?

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

int i,n,sum,search,num=0,ctr=0;

char answer,choice,choice2,search2;

struct record{

int s_id;
char s_name[100];
char s_course;
char s_college[5];
int s_scoress;
}id[100],name[100],course,college[100],scores;

struct s_scores{
int frst_grade;
int scnd_grade;
int fnl_grade;
}first,second,final;



void ADD();
void COLLEGE();
void ID();


void COLLEGE(){
printf("Enter college (abbreviation only)");
scanf("%s",&search2);
for(i=0;i<num;i++){
if(strcmp(college[i].s_college,search2)==0);
ctr++;    
}  
printf("The number of students in %s is %d",search2,ctr);
like image 859
Jose G. Avatar asked May 15 '16 09:05

Jose G.


1 Answers

Lets take a look at these (partial) lines:

char ..., search2;
...
scanf("%s",&search2);
...
...strcmp(college[i].s_college,search2)...

The variable search2 is a single character. Trying to put a string into it will write at least two character: The string you read plus the string terminator. That means you will write out of bounds.

You then use the character variable as an argument to strcmp which converts the contents of search2 into a pointer and uses that pointer as a pointer to a string.

Both of these problems will lead to undefined behavior.

Is search2 supposed to be a string? Then declare it as an array, like

char ..., search2[100];

If search2 is supposed to be a single character then first you need to read a single character

scanf("%c", &search2);  // Note the changed format to read a single character

And then you need to change your comparison to not use strcmp.

like image 124
Some programmer dude Avatar answered Oct 07 '22 03:10

Some programmer dude