以下是代码:
#include <stdio.h>
#include <stdlib.h>
void foo(int* ptr) {
printf("ptr is %x\n", ptr);
}
void main() {
int* ptr = (int*)malloc(sizeof(int));
printf("ptr is %x\n", ptr);
foo(ptr);
free(ptr);
}
......他是输出:
ptr is 0x007446c0
ptr is 0x00000000
......这就是问题:
为什么会发生这种情况?
答案 0 :(得分:3)
这是因为%x
中的printf
需要无符号整数,而不是指针。
以下是修复程序以获取所需行为的方法:
#include <stdio.h>
#include <stdlib.h>
void foo(int* ptr) {
printf("ptr is %p\n", (void*)ptr);
}
int main() {
int* ptr = malloc(sizeof(int));
printf("ptr is %p\n", (void*)ptr);
foo(ptr);
free(ptr);
return 0;
}
这是link to ideone;运行产生预期结果:
ptr is 0x8fa3008
ptr is 0x8fa3008
答案 1 :(得分:1)
因为你的程序会调用未定义的行为,所以我认为。这就是我认为你的意思:
#include <stdio.h>
#include <stdlib.h>
void foo(int* ptr) {
printf("ptr is %p\n", (void *) ptr); /* %x tells printf to expect an unsigned int. ptr is not an unsigned int. %p tells printf to expect a void *, which looks a little better, yeh? */
}
int main() { /* main ALWAYS returns int... ALWAYS! */
int* ptr = malloc(sizeof(int)); /* There is no need to cast malloc. Stop using a C++ compiler to compile C. */
printf("ptr is %p\n", (void *) ptr);
foo(ptr);
free(ptr);
}
这可以解决您的问题吗?