【发布时间】:2021-05-16 11:58:37
【问题描述】:
#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:%s\n", (*bird).isRinged);
printf("\tThe name of the specie:\n",(*bird).nameSpecies);
printf("\tThe birds age is:%d\n",(*bird).birdAgeMonths );
printf("Bird house info:\n");
printf("\tArea of its house is:%d\n",(*bird).hom.area);
printf("\tThe height of its house is:%d\n",(*bird).hom.height);
printf("\tThe quantity of feeders is:%d\n",(*bird).hom.feederquantity );
printf("\tThe house has nest:%s\n",(*bird).hom.hasNest );
printf("\tBird's gender is:%s\n",(*bird).gender );
}
我尝试添加任何可能的库(您可以在代码中看到它),但编译代码时仍然会发生错误。好吧,如果我们在主函数中重新编码该函数(使用所有已编辑的代码),它可以正常工作,但我希望它与一个单独的函数一起工作。你能帮我吗?
【问题讨论】:
-
如果
Bird.isRinged的长度为 1,则此strcpy(sparrow.isRinged,"T");会导致未定义的行为。请记住,strcpy 在字符串中的所有字符之后复制一个空字符。我怀疑您真的只想将其设为单个char而不是字符串。或者使用布尔值。 -
您必须在函数
main之外定义结构才能在main和printBird中使用它。顺便说一句:至少对于问题中显示的代码,您有几个不需要的#include指令。
标签: c struct scope declaration string-literals