首页 > 解决方案 > 如何在 C 中的另一个函数中打印数组结构

问题描述

我想在用户按下某个键(在这种情况下为 1)并停止循环后打印结构数组中的所有日期,如果他按下 2,则循环继续,直到数组变满或用户按下 1

#include <stdio.h>
#include <string.h >
struct dat {
    int age;
    char name[50];
    int score;
    int trab[2];
};

int main(void)
{
    int x = 0;
    struct dat people[20];
    for(int i = 0; i < 20; i++)
    {
        gets(people[i].name);
        scanf("%d", &people[i]age);
        scanf("%d", &people[i].score );
        scanf("%d", &people[i].trab[0]);
        scanf("%d", &people[i].trab[1]);
        scanf("%d", x);
        switch(x)
        {
            case 1:
                break;
            case 2:
                continue;
        }
    }
    imp(people[i]);
    return 0;
}

int imp(struct dat people[i])
{   
    int i;

    printf("%s", people[0].name);
    printf("%d", &people[0].age);
    printf("%d", &people[0].score );
    printf("%d", &people[0].trab[0]);
    printf("%d", &people[0].trab[1]);

    return 0;
}

标签: carraysprintf

解决方案


您的代码无法在此状态下编译。

你的编译器应该告诉你为什么有些行不能编译,首先尝试纠正错误。

纠正错误后,打开编译器警告并处理它们。


线

#include <string.h >

将引发此错误:fatal error: string.h : No such file or directory

为什么和之间有h空格>


gets不应使用该功能: from man gets

永远不要使用gets()。因为在事先不知道数据的情况下不可能知道gets()会读取多少个字符,而且因为gets()会继续存储超过缓冲区末尾的字符,所以使用起来非常危险。它已被用来破坏计算机安全。请改用 fgets()。

所以得到(people[i].name);

应该

fgets(stdin, people[i].name, sizeof people[i].name);

以下行缺少一个点.

scanf("%d", &people[i]age);

由于x为 0,因此下一行取消引用NULL 指针(您不想要):

scanf("%d", x);

你应该写:

scanf("%d", &x);

然后你调用imp函数 on people[i],但没有声明,并且 i 没有定义(它是循环imp的局部变量)for

imp(people[i]);

imp定义无效:

int imp(struct dat people[i])

应该是这样的:

/* function to display ONE person */
int imp(struct dat people)

或者

/* function to display ALL peopel */
int imp(struct dat *people, int number_of_people)

推荐阅读