基本用户名/密码代码在 C 语言中不起作用 - 分段错误



我两天前刚开始学习 C,并尝试编写一个代码,提示用户提交用户名和密码,然后将输入与存储的数据交叉引用。这个想法是,如果输入的用户名和密码匹配,则将打印"授予访问权限",如果不是,则打印"拒绝访问"。

但是,每当我使用输入测试代码时,我都会收到"访问被拒绝.分段错误"。关于为什么会发生这种情况的任何想法?附上我的代码以供参考:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <cs50.h>
int N;
typedef struct
{
string Username;
string Password;
}
LoginInfo;
int main(void)
{
LoginInfo code[N];
code[0].Username = "Agent X";
code[0].Password = "1314XN";
code[1].Username = "Agent Y";
code[1].Password = "1315YN";
code[2].Username = "Agent Z";
code[2].Password = "1316ZN";
code[3].Username = "Director A";
code[3].Password = "1414AN";
code[4].Username = "VP A";
code[4].Password = "1628VPN";
string User = get_string("Username: ");
string Pass = get_string("Password: ");
for (int i = 0; i < N; i++)
{
if((strcmp(code[i].Username, User) == 0) && (strcmp(code[i].Password, Pass) == 0))
{
printf("Access Granted.n");
return 0;
}
}
printf("Access Denied.");
return 1;
}

您已经定义了int N;但没有初始化它。由于它在全局范围内,因此给定的值为 0。

当您到达LoginInfo code[N];行时,N的值仍为 0,因此数组的大小为 0。访问数组的任何元素都会导致未定义的行为,并且可能是故障的来源。

在使用之前,您需要初始化N或以其他方式为其提供合理的值。例如:

int N = 5; // Initialize this!

通过此更改,您的代码可以干净地编译并运行。编译器资源管理器演示

您没有为 N 定义值,所以如果您希望 N 为 5,请将其更改为

#define N 5

如果没有 N 的值,则为 0(可能(,因此数组的大小为 0,您将始终遇到分段错误。

最新更新