Please explain why the following code gives the first mobile no. irrespective of entered name:
#include<stdio.h>
#include<conio.h>
int mobileno(char[]);
int main(){
char input[20];
gets(input);
printf("%s",input);
int x;
x = mobileno(input);
printf("%d",x);
switch(x){
case 0:printf("7255222319");break;
case 1:printf("9404521113");break;
case 2:printf("9326513553");break;
case 3:printf("9845621611");break;
case 4:printf("4556312390");break;
case 5:printf("9245178190");break;
case 6:printf("9214188214");break;
case 7:printf("7014773244");break;
case 8:printf("7898888044");break;
};
getch();
return 0;
}
int mobileno(char s[20]){
if( s="katrina" )
{return 1;}else{
if( s="shahid" ){return 2;}else{
if( s="ranbir" ){return 3;}else{
if( s="sharukh" ){return 4;}else{
if( s="hema" ){return 5;}else{
if( s="amitabh" ){return 6;}else{
if( s="shashnk" ){return 7;}else{
if( s="raj" ){return 8;}else{
if( s="aishwarya" ){return 0;}else{
return 9;}}}}}}}}};
};
You cannot compare strings using
=
(or even by==
, for that matter) operator. You need to usestrcmp()
for that.In your code, inside
mobileno()
function,is essentially trying to assign the base address of the string literal
"katrina"
tos
. It is nowhere near a comparison.That said,
gets()
, it suffer from buffer overflow problem. Use the safer alternative,fgets()
main()
isint main(void)