【问题标题】:comparing strings in a structure pointer in C比较C中结构指针中的字符串
【发布时间】: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)-&gt;user, ...) 中,p 是用户列表数组,n 是其中的条目数。你想要你的循环变量o,而不是:strcmp((p+o)-&gt;user, ...)。也就是说,我支持 Ken Y-N 的 cmets。作为命名的一般规则:变量范围越广,名称应该越解释。单字母循环变量可能没问题;全局变量应该有更好的名称,例如 user_listuser_count
  • 看起来你永远不会增加 h 或 o 或 *n,所以 o 将始终为 0,并且你的循环永远不会循环任何东西(任何你也会为你的 p 数组分配 0 个字节)。 ..
  • *n=&amp;h; 这不可能编译。请发布真实代码。 for (i;i&lt;=o;i++)i为什么是全局的,为什么这里没有初始化。
  • @oma 您的问题暗示问题出在您运行代码时。但是您发布的代码无法编译,更不用说运行了。所以没有人能猜出你遇到问题的真正代码是什么。当然这是一个问题,一个大问题。见How to create a Minimal, Reproducible Example

标签: c pointers structure realloc


【解决方案1】:

这段代码明显有误:

struct person *temp = realloc(p, *n * sizeof(struct person));

因为我们几乎马上要做:

scanf("%s",&(p+*n)->user);

这确实需要阅读

struct person *temp = realloc(p, (*n + 1) * sizeof(struct person));

另外,

for (i;i<=o;i++)

显然是错误的,应该是

for (i=0;i<=o;i++)

正如 dxiv 指出的那样,i 确实应该在此 for 循环中声明,而不是作为全局声明。

顺便说一句,您是否遇到了循环问题?我看不到main() 的递归调用。这真的很聪明,但是只有在使用优化(反过来更难调试)编译时,这段代码才能很好地工作。我建议更换

else{
    main();
}

以及对main() 的其他调用,并在整个main() 周围进行无限循环(最终将在输入阶梯上具有循环退出条件或条件break; 语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多