c - 如何在 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;
}
解决方案
您的代码无法在此状态下编译。
你的编译器应该告诉你为什么有些行不能编译,首先尝试纠正错误。
纠正错误后,打开编译器警告并处理它们。
线
#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)
推荐阅读
- reactjs - React Tinymce Quickbar 添加字体大小选项作为输入字段
- javascript - 有没有办法将我自己的帐户用于 twitch 聊天机器人?
- python - 将具有重复值的列表转换为数据框
- r - 在 Shiny 中,是否可以使会话中的变量对某些用户共享,但不是对所有用户共享?
- solr - TYPO3 Solr - 按文件扩展名分面
- python - 由于使用 pandas 的 python 中的 em-dashes / hypen 从 excel 读取时数据过滤器失败
- ceph - 如何在 LVM 卷上扩展 Ceph OSD
- c++ - 您如何在 timespec 结构中表示 -1 纳秒?
- python - 如何在 app.route 中分离烧瓶文件夹?
- c - 如何对使用 G_DECLARE_DERIVABLE_TYPE (glib/gobject) 定义的类进行子类化