【发布时间】:2017-11-17 08:24:11
【问题描述】:
我正在构建一个结构来保存电影的信息。当电影被打印时,它会递归地打印它的续集信息。
struct movie
{
char name[28];
int year;
struct movie* sequel;
};
void print_movie(struct movie film)
{
printf("Name: %s \n", film.name);
printf("Year of Release: %d \n", film.year);
if (film.sequel == 0)
{
printf("%s jas no sequel, yet! \n\n", film.name);
}
else
{
printf("%s's sequel was... \n\n", film.name);
print_movie(*film.sequel);
}
}
int main(void)
{
struct movie jurassic;
struct movie lostworld;
strcpy(jurassic.name, "Jurassic Park");
jurassic.year = 1993;
jurassic.sequel = &lostworld;
所有工作都按预期进行,直到这部分:
strcpy(lostworld.name, "The Lost World: Jurassic Park");
lostworld.year = 1997;
lostworld.sequel = 0;
print_movie(jurassic);
return 0;
}
我计算了《失落的世界:侏罗纪公园》(28) 中的字符数,并将其用作最大缓冲区。问题是,它不是动态的,当我执行程序时,它会打印 The Lost World: Jurassic Par- 并发出错误声音。
如果增加 char 缓冲区,例如增加到 29,我得到 Warning C4820: 'movie' : '3' bytes padding added after data member 'name' 我在 Visual Studio 中工作,出于学习目的,我已将编译器设置为将警告评估为错误,并且我使用了 _CRT_SECURE_NO_WARNINGS。
这里发生了什么?我应该使用 malloc 作为字符吗?谢谢
【问题讨论】:
-
I've counted the number of characters in 'The Lost World: Jurassic Park' (28)再次计数。 -
"The Lost World: Jurassic Park"的长度为 29。并且需要 +1 即 30. -
与您的问题没有直接关系 - 但出于实际原因,您可能应该让
print_movie函数接受一个指针,而不是将整个列表复制到堆栈中 -
您正在使用一个字符数组来保存一个字符串。但是字符串有开销,你需要空间来承受开销。
标签: c visual-studio recursion struct char