#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <limits.h>
#include <stdlib.h>
#include <math.h>
#include <sys/io.h>
#include <fcntl.h>
int main(){
struct BirdHome{
int area;
int height;
int feederquantity;
char hasNest[1];
};
struct Bird{
char isRinged[1];
char nameSpecies[50];
int birdAgeMonths;
struct BirdHome hom;
char gender[1];
};
struct Bird sparrow;
strcpy(sparrow.isRinged,"T");
strcpy(sparrow.nameSpecies,"sparrow");
sparrow.birdAgeMonths=4;
sparrow.hom.area=30;
sparrow.hom.height=20;
sparrow.hom.feederquantity=2;
strcpy(sparrow.hom.hasNest,"F");
strcpy(sparrow.gender,"M");
printBird(&sparrow);
return 0;
}
void printBird(struct Bird *bird){
printf("Bird info:n");
printf("tIs bird ringed:%sn", (*bird).isRinged);
printf("tThe name of the specie:n",(*bird).nameSpecies);
printf("tThe birds age is:%dn",(*bird).birdAgeMonths );
printf("Bird house info:n");
printf("tArea of its house is:%dn",(*bird).hom.area);
printf("tThe height of its house is:%dn",(*bird).hom.height);
printf("tThe quantity of feeders is:%dn",(*bird).hom.feederquantity );
printf("tThe house has nest:%sn",(*bird).hom.hasNest );
printf("tBird's gender is:%sn",(*bird).gender );
}
我已经尝试添加任何可能的库(您可以在代码中看到),但在编译代码时仍然会出现错误。好吧,如果我们在主函数中重新编码(使用所有经过编辑的代码),它可以正常工作,但我希望它使用一个单独的函数。你能帮我吗?
类型struct Bird的作用域是函数main的外部块作用域。
int main(){
struct BirdHome{
int area;
int height;
int feederquantity;
char hasNest[1];
};
struct Bird{
char isRinged[1];
char nameSpecies[50];
int birdAgeMonths;
struct BirdHome hom;
char gender[1];
};
//...
因此,在函数主体之外,类型struct Bird
是未声明和未定义的。
然而,在应该在函数main
之前声明的函数printBird
的定义中,您试图使用结构的数据成员,尽管在这个范围中,main中声明的struct Bird
是未声明和未定义的。
void printBird(struct Bird *bird){
printf("Bird info:n");
printf("tIs bird ringed:%sn", (*bird).isRinged);
//..
这是在您声明的不完整类型struct Bird
的函数参数列表中
void printBird(struct Bird *bird){
^^^^^^^^^^^
它与main中声明的CCD_ 6没有任何共同之处。
从main
移动结构定义,使其定义可用于函数printBird
。然后将函数声明放在函数main
之前。
同样,由于结构类型的对象是通过引用传递给函数的,并且在函数中没有更改,因此应该使用quakifier const
void printBird( const struct Bird *bird);
注意这个调用
strcpy(sparrow.isRinged,"T");
调用未定义的行为,因为数组CCD_;T";其内部表示为具有两个元素CCD_ 11的字符阵列。
你应该至少像一样申报
char isRinged[2];
的这些语句也存在同样的问题
strcpy(sparrow.hom.hasNest,"F");
strcpy(sparrow.gender,"M");
您需要放大已使用的字符数组。