代码如下:
#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
...问题是:
为什么这会发生在我身上???
最佳答案
发生这种情况是因为 printf
中的 %x
需要一个无符号整数,而不是指针。
这里是如何修正你的程序以获得你想要的行为:
#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
关于c - 传递的参数更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15571012/