我正在学习指针,我正在从教程中运行这个程序,它提供了一些有趣的输出.
#includeint main () { int var = 20; /*actual variable declaration */ int *ip; /*pointer variable declaration*/ ip = &var; /*store addres of var in ip variable*/ printf("Address of var variable: %x\n", &var); /*address stored in ip variable*/ printf("Address of stored in ip variable: %x\n", ip); /*access the value using pointer */ printf("value of *ip variable: %x\n", *ip); return 0; }
根据我的理解,该网站说我的输出应该是两个匹配的内存位置,而值为20的"**ip变量"部分.我对内存位置没有任何问题,它们都像人们想象的一样,最后一部分,它告诉我*ip变量的值是14?
Address of var variable: 6d73b8cc Address of stored in ip variable: 6d73b8cc value of *ip variable: 14
这里发生了什么?用gcc编译,它给出一个关于格式%x的警告,期望一个无符号整数,但参数2的类型为....
MorePointers.c:10:9: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=] printf("Address of var variable: %x\n", &var); ^ MorePointers.c:13:9: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=] printf("Address of stored in ip variable: %x\n", ip);
请纠正我,如果我错了,但可能是由于格式,当期望无符号整数时可能导致数字不是20?作为无符号整数的值在0到65,535或0到4,294,967,295之间,而整数在-32,768到32,767或-2,147,483,648到2,147,483,647之间?
发生的事情是您将整数值打印20
为十六进制值,正确显示为14
.我怀疑你在期待20
十进制.:)
一些修复: -
printf("Address of var variable: %x\n", &var);
这是不正确的,应该将指针打印为指针值
printf("Address of var variable: %p\n", &var); /* << ensure pointer value */
当你打电话时printf
,它会将固定文本和参数按顺序混合......
printf( "hello %d world %d today %d\n", 1,2,3 );
今天打印你好1世界2 3
显示参数的方式基于格式说明符.
%s /* displays as a string */ %d /* displays as an integer in normal decimal */ %x /* displays an integer in hexa-decimal. */ %f /* displays as a floating point */ %p /* displays a pointer address */ Decimal goes 0,1,2,..,8,9,10,11,...,14,15,16,17,...,20 Hexadecimal goes 0,1,2,..,8,9, A, B,..., E, F,10,11,...,14