如何打印C变量的地址? [英] How to print variable addresses in C?

查看:142
本文介绍了如何打印C变量的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行这个code。

When i run this code.

#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);
}

我保持我的编译器收到此错误。

I keep getting this error in my compiler.

/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 *’

你能帮助我吗?

感谢

blargman

推荐答案

您想要使用%P 打印指针。从规格:

You want to use %p to print a pointer. From the spec:

P 参数应该是一个指针为 无效 。指针的值被转换成打印字符的序列,在一个实现定义方式。

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

而且不要忘了投,例如

printf("%p\n",(void*)&a);

这篇关于如何打印C变量的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆