我目前正在阅读《黑客攻防技术宝典》,其中有一个例子我似乎无法正确地实现。尝试编译时会出现以下错误:
./addressof.c: In function ‘main’:
./addressof.c:8:4: warning: format ‘%x’ expects argument of type ‘unsigned int’,
but argument 2 has type ‘int *’ [-Wformat]
#include <stdio.h>
int main() {
int int_var = 5;
int *int_ptr;
int_ptr = &int_var; // Put the address of int_var into int_ptr.
printf("int_ptr = 0x%08x\n", int_ptr);
printf("&int_ptr = 0x%08x\n", &int_ptr);
printf("*int_ptr = 0x%08x\n\n", *int_ptr);
printf("int_var is located at 0x%08x and contains %d\n", &int_var, int_var);
printf("int_ptr is located at 0x%08x, contains 0x%08x, and points to %d\n\n",
&int_ptr, int_ptr, *int_ptr);
}
我知道错误出在哪里,但是不确定该如何修复。
%p
格式说明符打印*int_ptr
(即int
)。int_ptr
和&int_ptr
是指针,必须使用%p
进行打印,但指针指向的值是一个整数,必须使用%d
进行打印。 - Praetorianprintf
时,您必须将任何指针转换为void
指针进行强制转换:printf("%p", (void*)(&x));
。不同的指针类型不需要以相同的方式布局,但是它们确实保证可以无损地转换为void*
。 - Kerrek SB%8p
而不是%08p
(前导零不支持p
说明符)。 - Nicolas Miari