c 断错误 demo
2021年10月8日20:55:05 星期五
一个简单的段错误例子。
示例:
// demo.c
#include <stdio.h>
struct fruit {
int weight;
char name[32];
};
int main()
{
struct fruit fru[2] = {
{ .weight = 10, .name = "pear" },
{ .weight = 8, .name = "apple" }
};
for(int i = 0; i < sizeof(fru)/sizeof(struct fruit); i++)
{
printf("%d. %s:%d\n", fru[i].name, fru[i].weight);
}
return 0;
}
提问:这个代码有没有 bug?
答案:当然有,而且会产生错误。
正确代码
#include <stdio.h>
struct fruit {
int weight;
char name[32];
};
int main()
{
struct fruit fru[2] = {
{ .weight = 10, .name = "pear" },
{ .weight = 8, .name = "apple" }
};
for(int i = 0; i < sizeof(fru)/sizeof(struct fruit); i++)
{
printf("%d. %s:%d\n", i, fru[i].name, fru[i].weight);
}
return 0;
}
效果
$ gcc demo.c
$ ./a.out
0. pear:10
1. apple:8
网友评论