【问题标题】:writing to strings inside a structure doubly linked list in C在C中写入结构双向链表中的字符串
【发布时间】:2015-07-09 11:59:55
【问题描述】:

我的代码有问题,我更改了一些函数以适应我添加的结构,所以不是到处都有变量,但现在它根本不起作用。我需要它来创建一个结构人员,然后它提示用户输入人员姓名和年龄;然后它要求更多的人填写一个双向链表,如果没有输入人名,则停止循环。然后它吐出与我输入双向链表的内容相反的内容。感谢所有帮助^-^

struct person
{
    char name[10][41];
    int age[10];
};

int write(struct person *people);
void print(struct person *people);
int main(void)
{
    char names[10][41];
    int n = 10;
    int ages[10];

    typedef struct person people;

    n = write(people);
    print(people);


    system("PAUSE");
    return 0;
}


int write(struct person *people)
{
    int i;
    char name[41];
    int age[10];
    for(i=0; i<=i; i++)
    {
        fflush(stdin);
        printf("Enter full name\n");

        gets(people.name);
        strcpy(names[i], name);

        if(names[i][0] == '\0')
            break;

        printf("Enter their age\n");
        scanf("%d", &age[i]);
        ages[i] = age[i];
    }
}

void print(struct person *people)
{
    int i = 0;
    for(i = 0; i < 10; i++)
    {
        if(names[i][0] == '\0')
            break;

        printf("%s is %d year(s) old\n", names[i], ages[i]);
    }
    return i;
}

【问题讨论】:

  • 这是什么:for(i=0; i&lt;=i; i++)
  • 正在使用它来测试我的循环,直到我知道它有效之前不想更改它

标签: c list function struct


【解决方案1】:
  1. 您传递的是您刚刚定义的类型的名称,而不是声明为该类型的变量,this

    typedef struct person people;
    

    应该是

    struct person people;
    
  2. 改变

    n = write(people);
    

    n = write(&people);
    
  3. 删除 fflush(stdin) 这是未定义的行为。

  4. 不要使用gets(),这很不安全,请改用fgets()

    char name[40];
    gets(name);
    

    应该是

    char name[40];
    fgets(name, sizeof(name), stdin);
    

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2016-01-16
    • 1970-01-01
    • 2012-05-20
    • 2019-05-02
    • 1970-01-01
    • 2013-09-01
    • 2020-10-09
    • 2016-04-11
    相关资源
    最近更新 更多