【发布时间】:2021-04-02 13:07:42
【问题描述】:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct person {
char user[50];
char password[50];
int amount;
};
int i=0;
int h=0;
int *n=&h;
struct person *p = NULL;
void adduser();
int main()
{
int x;
printf("Welcome to the bank\n");
printf("what would you like to do\n");
printf("type 1 to add a user\n");
printf("type 2 to add to balance\n");
printf("type 3 to take from balance\n");
printf("type 4 to check from balance\n");
scanf("%d%*c",&x);
if(x==1){
adduser();
}
else if (x == 2){
printf("2");
}
else if (x == 3){
printf("3");
}
else if (x == 4){
printf("4");
}
else{
main();
}
}
void adduser(){
struct person *temp = realloc(p, *n * sizeof(struct person));
if (temp != NULL)
p = temp;
printf("n=%d\n",*n-1);
printf("enter your new username\n");
scanf("%s",&(p+*n)->user);
int o=*n-1;
for (i;i<=o;i++)
{
if(strcmp((p+*n)->user,(p+i)->user) == 0)
{
printf("user already exists");
adduser();
}
}
printf("enter your new password\n");
scanf("%s",(p+*n)->password);
*n+=1;
main();
}
你好,我是 C 的初学者,我正在尝试使用此代码查看我的用户输入字符串与我的结构中的用户输入类似。
for (i;i<=o;i++)
{
if(strcmp((p+*n)->user,(p+i)->user) == 0)
{
printf("user already exists");
adduser();
}
}
我的代码应该要求用户输入他们的新用户(至少是我发布的内容)并检查是否存在类似的用户,但我的循环被忽略了,我不知道如何处理它。我觉得我的问题出在其他地方,但我无法弄清楚。我也可能犯了根本性的错误,因为我对结构和指针非常陌生。
我尝试在网上搜索解决方案,但找不到类似的情况。
【问题讨论】:
-
1.请使用有意义的变量名。 2. 请使用函数参数,而不是全局参数。 3.请使用标签。 4.你
realloc()有多少内存? -
在您的
strcmp((p+*n)->user, ...)中,p是用户列表数组,n是其中的条目数。你想要你的循环变量o,而不是:strcmp((p+o)->user, ...)。也就是说,我支持 Ken Y-N 的 cmets。作为命名的一般规则:变量范围越广,名称应该越解释。单字母循环变量可能没问题;全局变量应该有更好的名称,例如user_list或user_count。 -
看起来你永远不会增加 h 或 o 或 *n,所以 o 将始终为 0,并且你的循环永远不会循环任何东西(任何你也会为你的 p 数组分配 0 个字节)。 ..
-
*n=&h;这不可能编译。请发布真实代码。for (i;i<=o;i++)i为什么是全局的,为什么这里没有初始化。 -
@oma 您的问题暗示问题出在您运行代码时。但是您发布的代码无法编译,更不用说运行了。所以没有人能猜出你遇到问题的真正代码是什么。当然这是一个问题,一个大问题。见How to create a Minimal, Reproducible Example。
标签: c pointers structure realloc