如何在C中的另一个函数中打印数组结构

时间:2018-12-17 00:17:35

标签: c arrays printf

我想在用户按某些键(在这种情况下为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;
}

1 个答案:

答案 0 :(得分:2)

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

您的编译器应告诉您为什么某些行不编译,请首先尝试更正错误。

更正错误后,打开编译器警告并进行处理。


#include <string.h >

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

为什么h>之间有空格?


不应使用函数gets:从man gets

  

请勿使用gets()。因为无法不事先知道数据就无法知道将读取多少个字符gets(),并且因为gets()将继续存储超过缓冲区末尾的字符,所以使用它非常危险。它已被用来破坏计算机的安全性。使用fgets()代替。

所以     gets(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上调用people[i]函数,但未声明imp,并且未定义i(这是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)