基本 Username/Password 代码在 C 中不起作用 - 分段错误
Basic Username/Password Code not working in C - Segmentation Fault
我 2 天前才开始学习 C,并尝试编写一段代码,提示用户提交用户名和密码,然后交叉引用输入和存储的数据。这个想法是,如果输入的用户名和密码匹配,那么 "Access Granted" 将被打印,如果不匹配,则 "Access Denied".
但是,每当我使用输入测试代码时,我都会收到 "Access Denied.Segmentation fault"。关于为什么会发生这种情况的任何想法?在下面附上我的代码以供参考:
#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;
}
您没有为 N 定义值,因此如果您希望 N 为 5,请将其更改为
#define N 5
如果 N 没有值,则为 0(可能),因此数组的大小为 0,您将始终遇到分段错误。
您已定义 int N;
但未对其进行初始化。因为它在全局范围内,所以它的值为 0。
当您到达行 LoginInfo code[N];
时,N
的值仍然为 0,因此数组的大小为 0。访问数组的任何元素都会导致未定义的行为,并且很可能故障根源。
您需要初始化 N
或者在使用前给它一个合理的值。例如:
int N = 5; // Initialize this!
通过此更改,您的代码可以干净地编译并运行。 Demo on Compiler Explorer
我 2 天前才开始学习 C,并尝试编写一段代码,提示用户提交用户名和密码,然后交叉引用输入和存储的数据。这个想法是,如果输入的用户名和密码匹配,那么 "Access Granted" 将被打印,如果不匹配,则 "Access Denied".
但是,每当我使用输入测试代码时,我都会收到 "Access Denied.Segmentation fault"。关于为什么会发生这种情况的任何想法?在下面附上我的代码以供参考:
#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;
}
您没有为 N 定义值,因此如果您希望 N 为 5,请将其更改为
#define N 5
如果 N 没有值,则为 0(可能),因此数组的大小为 0,您将始终遇到分段错误。
您已定义 int N;
但未对其进行初始化。因为它在全局范围内,所以它的值为 0。
当您到达行 LoginInfo code[N];
时,N
的值仍然为 0,因此数组的大小为 0。访问数组的任何元素都会导致未定义的行为,并且很可能故障根源。
您需要初始化 N
或者在使用前给它一个合理的值。例如:
int N = 5; // Initialize this!
通过此更改,您的代码可以干净地编译并运行。 Demo on Compiler Explorer