c - 传递的参数更改值

标签 c visual-studio-2010 pointers memory parameters

代码如下:

#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/

相关文章:

c++ - C/C++ 链接约定

c++ - 使用 Visual Studio 2015 Win64 编译 MySQL Connector

c# - MVC : Need to build my application with multiple projects

visual-studio-2010 - 将菜单按钮添加到 VS2010 TFS 查询结果或工作项栏

C++ 比较成员函数指针

c++ - 按矩阵类型转换矩阵乘法,C++

C——指针+1的含义

c - 从 C 中的字符串中提取数字

c - 在数据结构中使用数组成员

visual-studio-2010 - 使用 VS 2010 和 FindRibbons 构建错误