如何在C中打印变量地址?

nam*_*run 42 c pointers memory-address

当我运行此代码.

#include <stdio.h>

void moo(int a, int *b);

int main()
{
    int x;
    int *y;

    x = 1;
    y = &x;

    printf("Address of x = %d, value of x = %d\n", &x, x);
    printf("Address of y = &d, value of y = %d, value of *y = %d\n", &y, y, *y);
    moo(9, y);
}

void moo(int a, int *b)
{
    printf("Address of a = %d, value of a = %d\n", &a, a);
    printf("Address of b = %d, value of b = %d, value of *b = %d\n", &b, b, *b);
}
Run Code Online (Sandbox Code Playgroud)

我一直在编译器中收到此错误.

/Volumes/MY USB/C Programming/Practice/addresses.c:16: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’
/Volumes/MY USB/C Programming/Practice/addresses.c:17: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int **’
/Volumes/MY USB/C Programming/Practice/addresses.c:17: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int *’
/Volumes/MY USB/C Programming/Practice/addresses.c: In function ‘moo’:
/Volumes/MY USB/C Programming/Practice/addresses.c:23: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’
/Volumes/MY USB/C Programming/Practice/addresses.c:24: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int **’
/Volumes/MY USB/C Programming/Practice/addresses.c:24: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int *’
Run Code Online (Sandbox Code Playgroud)

你可以帮帮我吗?

谢谢

blargman

Car*_*rum 85

您想用来%p打印指针.从规格:

p 参数应该是指针void.指针的值以实现定义的方式转换为打印字符序列.

并且不要忘记演员表,例如

printf("%p\n",(void*)&a);
Run Code Online (Sandbox Code Playgroud)

  • +1:......但是为了便携性(并遵循标准中的**SHALL**),不要忘记施放地址.`的printf( "%P \n" 个,(无效*)&一个);` (8认同)
  • @Carl:在可变函数中,编译器无法检查针对期望类型的参数类型.对`void*`的强制转换不是自动的:变量函数中的自动变量是`int`和`float`到`double`的一些低范围整数. (6认同)
  • @pmg,是演员必备的吗?我认为往返于'void*'的转换在C中是安全和自动的(6.3.2.2第1段). (3认同)
  • @blargman,是的,这是错的.您可能能够通过类型转换强制进行工作,但由于`%d`用于打印有符号整数,因此它可能不是一个好的选择. (2认同)

小智 6

当您打算打印任何变量或指针的内存地址时,使用%d将不会执行该作业并将导致一些编译错误,因为您尝试打印出一个数字而不是一个地址,即使它确实有效,你有一个意图错误,因为内存地址不是数字.价值0xbfc0d878肯定不是数字,而是地址.

你应该使用的是什么%p.例如,

#include<stdio.h>

int main(void) {

    int a;
    a = 5;
    printf("The memory address of a is: %p\n", (void*) &a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

祝好运!

  • 值"0xbfc0d878"*是*数字.`(void*)0xbfc0d878`不是.并且`%p`可能使用看起来像数字(通常是十六进制)的人类可读表示,但这并不意味着指针是数字.(顺便说一句,这个问题已在两年多前得到解答.) (3认同)