I have a function named Login() that reads a username(ex. "John"
) and then create a password that is the username itself with each letter upper or lower in random (ex. "JoHn"
)inside a new function called password()
.However when I try to print the password in Login() as a return statement from password()
it prints null;
This is the function that returns the password :
void Login()
{
char passwd[20];
char name[20];
printf(" Please enter your username : \n");
do
{
scanf(" %s",&name);
}while(strcmp(name,"John")!=0);
printf("Your password is : %s\n",password(name));
printf("Please enter your password : \n");
do
{
scanf(" %s",&passwd);
}while(strcmp(passwd,password(name))!=0);
}
And this is the function that returns the password :
char password( char pass[])
{
int i;
int k;
for(i=0;i<strlen(pass);i++)
{
k= rand()%2;
if(k==1)
{
pass[i]=toupper(pass[i]);
}
else{
pass[i]=tolower(pass[i]);
}
}
return pass;
}
Now when I run Login()
in main
i get
"Your password is : (null)"
How can I fix this problem ?
The primary issue: Your password()
function actually return a char
, whereas it is supposed to return a pointer to the first element of a char
array (modified one).
That said, there are other issues.
You call password(name)
multiple times (in do...while
loop), whereas, your input is supposed to be validated against the result of the first call. As in every call, the returned string is randomized, successive calls will return different results. You need to store the result of the first call and compare the input against it.
scanf(" %s",&name);
should be scanf("%19s",name);
, because
19
will length-limit the input, avoiding possible buffer overflows.&
is not needed.Same for password input also.
EDIT:
Here is a working version of the code: Live version
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char* password( char pass[])
{
int i;
int k;
for(i=0;i<strlen(pass);i++)
{
k= rand()%2;
if(k==1)
{
pass[i]=toupper(pass[i]);
}
else{
pass[i]=tolower(pass[i]);
}
}
return pass;
}
int main(void)
{
char passwd[20];
char name[20];
printf(" Please enter your username : \n");
do
{
scanf("%19s",name);
}while(strcmp(name,"John")!=0);
char * res = password(name);
printf("Your password is : %s\n",res);
do
{
printf("Please enter your password : \n");
scanf("%19s",passwd);
}while(strcmp(passwd,res)!=0);
return 0;
}