今天看第三章《数据》,定义了一个枚举类型,打印出来竟然是:Segmentation fault
于是用gdb调试了一下,发现错误出在printf下:
[root@bjxdurs235 c-study]# gdb enum_declaration
GNU gdb Red Hat Linux (6.3.0.0-1.63rh)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/tls/libthread_db.so.1".
(gdb) l 1
1 #include
2 int main(void)
3 {
4 /* example 1
5 enum MONNEY { ONE=1, TWO, FIVE=5, TEN=10 };
6 printf("TWO:%d",TWO);
7 */
8
9 enum Liquid { OUNCE = 1, CUP = 8, PINT =16,
10 QUART =32, GALLON = 128 };
(gdb)
11 enum Liquid jar;
12 jar = QUART;
13 printf("jar:%s\n",jar);
14 jar = jar + PINT;
15 printf("jar:%s\n",jar);
16
17 }
(gdb)
Line number 18 out of range; enum_declaration.c has 17 lines.
(gdb) start
Breakpoint 1 at 0x8048384: file enum_declaration.c, line 12.
Starting program: /home/liufeng/c-study/enum_declaration
main () at enum_declaration.c:12
12 jar = QUART;
(gdb) i locals
jar = 7052448
(gdb) p QUART
$1 = QUART
(gdb) n
13 printf("jar:%s\n",jar);
(gdb) p jar
$2 = QUART
(gdb) i locals
jar = QUART
(gdb) p QUART
$3 = QUART
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00729e53 in strlen () from /lib/tls/libc.so.6
看了课后的答案知道了不能用%s打印,晕倒了,但是不明白为什么我p jar的时候出来的是QUART哦,哦,知道了,QUART被当成了命名常量了吧,改用%d %c打印就没有问题了:
[root@bjxdurs235 c-study]# vi enum_declaration.c
#include
int main(void)
{
/* example 1
enum MONNEY { ONE=1, TWO, FIVE=5, TEN=10 };
printf("TWO:%d",TWO);
*/
enum Liquid { OUNCE = 1, CUP = 8, PINT =16,
QUART =32, GALLON = 128 };
enum Liquid jar;
jar = QUART;
printf("jar:%d\n",jar);
jar = jar + PINT;
printf("jar:%c\n",jar);
}
~
~
~
"enum_declaration.c" 17L, 307C written
[root@bjxdurs235 c-study]# gcc enum_declaration.c
[root@bjxdurs235 c-study]# ./a.out
jar:32
jar:0
这个小小的简单程序学会了枚举类型的用法:
enum ENUM_type { a , b , c ,d};
enum ENUM_type i;
i = b;
这样来用,而且a,b,c,d都可以直接使用,类似这样吧:
#define a 0
#define b 1
...
阅读(1607) | 评论(0) | 转发(0) |