Like what the title said, I was trying to make a signup system but for some reason it overwrites the array which was supposed to be defaultuser[0] = "12291955" it becomes what I inputted except I wanted it to go to defaultuser[3] (denoted by x = 3). So basically, the signup system is supposed to add a 4th user. (The following is a header file for my main.c file)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
void loginsystem(){
char defaultuser[][100] = {"12291995", "12221999", "12241344"};
char defaultpass[][100] = {"test1", "test2", "test3"};
int i = 0, indicator = 1, x = 3;
char userinput[20], passinput[20], choicest[20], prog[20];
const char* choicecmp;
system("cls");
printf("\nSystem");
printf("\nWould you like to create an account or log into an existing account? (Type Signup or Login) ");
scanf(" %[^\n]s", choicest);
printf("%d", x); //x=3
choicecmp = strlwr(choicest);
if(strcmp(choicecmp, "signup")==0 || strcmp(choicecmp, "sign up") == 0 )
{
//system("cls");
printf("\nEnter your ID Number: ");
scanf(" %s", defaultuser[x]);
printf("\nEnter your password: ");
scanf(" %s", defaultpass[x]);
getch();
choicecmp = "login";
x++;
printf("%d", x); //x becomes 1 for some reason
getch();
}
if(strcmp(choicecmp, "login")==0 || strcmp(choicecmp, "log in") == 0 ){
do{
system("cls");
printf("\nPlease login!");
printf("\n\nUsername (ID Number): ");
scanf(" %s", &userinput);
printf("\nPassword: ");
do{
passinput[i] = getch();
if(passinput[i] != '\r')
printf("*");
i++;
}while(passinput[i-1] != '\r');
passinput[i-1] = '\0';
for(int i = 0; i < x; i++){
if(strcmp(userinput, defaultuser[i]) == 0 && strcmp(passinput, defaultpass[i]) == 0)
{
system("cls");
indicator = 0;
printf("\nWelcome back User");
}}
return ;
}
I tried debugging the code and turns out that int x = 3 became x=0 along the way in the signup system, and became 1 after the x++.
defaultuser
has three elements.
char defaultuser[][100] = {"12291995", "12221999", "12241344"};
But you try to write to the fourth element.
int x = 3;
scanf(" %s", defaultuser[x]);
This is undefined behaviour.