I'm trying to build a program with C but I'm having trouble changing a char array into a char pointer and adjusting the program accordingly. Here's my current code that I want to change:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
char username[20];
char password[20];
char username_input[20];
char password_input[20];
char user_input;
void create_account(char* usrname, char* passwd) {
printf("==================================CREATE BANK ACCOUNT==================================\n");
while(1) {
printf("Enter a username that is less than 20 characters: ");
scanf("%s", usrname);
if (strlen(usrname) <= 20)
break;
printf("That is not less than 20 characters, try again...\n");
sleep(2);
}
while(1) {
printf("Enter a password that is less than 20 characters: ");
scanf("%s", passwd);
if (strlen(passwd) <= 20) {
break;
}
printf("That is not less than 20 characters, try again... \n");
sleep(2);
}
printf("Thank you, please sign in now...\n");
sleep(2);
}
void login() {
while(1) {
printf("Enter Username: ");
scanf("%s", username_input);
printf("Enter Password: ");
scanf("%s", password_input);
if (strcmp(username, username_input) != 0 || strcmp(password, password_input) != 0) {
printf("Incorrect Username or Password. Try again...\n");
sleep(2);
}
else {
printf("Welcome %s\n", username);
sleep(2);
break;
}
}
}
On the lines at the beginning, you can see that there are 4 char array declarations. I want them to be char pointers like so:
char* username;
char* password;
char* username_input;
char* password_input;
The reason for this is because I don't want a limit in a string, but arrays need limits. Once I change that, I want to use malloc()
to allocate memory for what the user inputs but I don't know how. In other words, I want to declare a char pointer that accepts user input. And I want enough memory to be allocated for that pointer so that the string that was inputted has enough space. Also I want my code to be compatible with different compilers and computers. For that I'm pretty sure that I have to multiply the malloc()
function with sizeof(char)
or something like that. I don't necessarily get an error, as in I don't get red lines in my IDE, but the program stops in the middle of it for no reason and gives me an exit code other than 0.