如何在C程序中打印指针地址? [英] How to print pointer address in a C program?

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

问题描述

我正在尝试学习如何在C程序中(使用)指针.我的示例如下:

I'm trying to learn how to (use) the pointer in a C program; my example is as follows:

   #include <stdio.h>
   #include <stdlib.h>

   int main(int argc, char *argv[]) {
        int * tab = (int*)malloc(sizeof(int)*5);
        int a =10;
        int *p;
        p  = &a;
        printf("the adress of a is%d \n",&a);    
        printf("the adress of a using the pointer is%p \n",p);    
        printf("the adress of tab is%d \n",tab);    
    }

我正在尝试打印a的地址,p的地址以及tab的第一个字节的开始位置.

I'm trying to print the address of a, the address of p and where the first byte of the tab begins.

使用"%p"时我可以得到十六进制值,但是我愿意使用地址的十进制值.

I can get hexadecimal values when using "%p", but I'm willing the decimal value of the addresses.

:在此视频 图像,有人使用"%d"打印十进制值一个指针地址,这让我感到困惑.

Edit : On this Video image, someone has used "%d" to print a decimal value for a pointer address, and it has confused me.

推荐答案

要打印对象指针的十进制版本,请先将指针转换为整数.最好使用可选类型uintptr_t.

To print a decimal version of an object pointer, 1st convert the pointer to an integer. Best to use the optional type uintptr_t.

以下类型(uintptr_t)指定一个无符号整数类型,其属性是可以将任何有效的指向void的指针转换为该类型(uintptr_t)... C11dr§7.20.1.41

The following type (uintptr_t) designates an unsigned integer type with the property that any valid pointer to void can be converted to this type (uintptr_t) ... C11dr §7.20.1.4 1

#include <inttypes.h>
uintptr_t d = (uintptr_t)(void *) &a;

然后打印.
有关 PRIuPTR

Then print it.
Some info on PRIuPTR

printf("%" PRIuPTR "\n", d);


对于C99之前的代码,请考虑直接转换为unsigned long. @Barmar


For pre-C99 code, consider a direct cast to unsigned long. @Barmar

OP稍后发表了评论

"......我将尝试操作tab变量,并且我将测试tab中的每个单元格是否为4字节,因此可能是我将执行tab + 8字节来获取特定单元格的值,在这里这是一个简单的示例,使用十进制对我来说将很容易."

"... i will try to manipulate the tab variable , and i will test if every cell in the tab is 4 byte , so may be i will do tab+8 bytes to get the value of a specific cell , here it's a simple example , with decimal it will be easy for me ."

这是一个有问题的方法,因为指针的十进制可能无法提供预期的连续数字模型.这篇文章可能对学习很有帮助,但是OP在另一篇文章中提供了更多细节,对于更高级别的问题,甚至可以给出更好的主意.

This is a questionable approach as the decimalization of a pointer may not provide the continuous numeric model expected. This post this may be good for learning, but with OP providing more details in another post, even better ideas could be given for the higher level problem.

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

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