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

查看:94
本文介绍了如何在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 address of a is %d \n",&a);    
        printf("the address of a using the pointer is %p \n",p);    
        printf("the address of tab is %d \n",tab);    
    }

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

I'm trying to print the address of a, the address value inside 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.4 1

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

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

<小时>

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

OP 稍后评论

"...我将尝试操作选项卡变量,并且我将测试选项卡中的每个单元格是否为 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天全站免登陆