[英]Passing structures between functions
I was trying to learn how structures are passed between functions and I wrote a program where there is an array of structure and structure itself has an array of integers.It is compiling properly but when I run it,the program is not expecting more than 4 values.I dont know what the error is? 我试图学习如何在函数之间传递结构,并且我写了一个程序,其中有一个结构数组,而结构本身有一个整数数组。它可以正确编译,但是当我运行它时,该程序期望不超过4值。我不知道错误是什么?
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
char bname[10];
int ssn[3];
} book;
void accept(book k[], int n);
void print(book k[], int n);
int main()
{
book a[2];
accept(a, 2);
print(a, 2);
return 0;
}
void accept(book k[], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < 3; i++)
{
scanf("%d\n", &k[i].ssn[j]);
}
scanf("%s\n", k->bname);
}
}
void print(book k[], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d\n", k[i].ssn[j]);
}
printf("%s\n", k->bname);
}
}
Your accept
function: 您的
accept
功能:
for (j = 0; j < 3; i++) // infinite loop
Should be j ++ . 应该是j ++。
Next, in both accept
and print
change k->bname
to k[i].bname
, so as not to rewrite always the first object. 接下来,在
accept
和print
将k->bname
更改为k[i].bname
,以免始终重写第一个对象。
And as already pointed out in comments by @SouravGhosh why use scanf("%d\\n"...
- it can be just scanf("%d"...
. 正如@SouravGhosh在评论中所指出的,为什么要使用
scanf("%d\\n"...
它可以只是scanf("%d"...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.