我正在尝试学习如何在 C 程序中使用指针;我的例子如下:
#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
的第一个字节开始的位置.
使用 "%p"
时我可以获得十六进制值,但我愿意使用地址的十进制值。
最佳答案
要打印对象指针的十进制 版本,首先将指针转换为整数。最好使用可选类型 uintptr_t
。
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后来评论
"...我将尝试操作 tab 变量,并且我将测试 tab 中的每个单元格是否都是 4 字节,所以我可能会执行 tab+8 字节以获得特定单元格的值,这里这是一个简单的例子,使用小数对我来说很容易。”
这是一种有问题的方法,因为指针的十进制化可能无法提供预期的连续数字模型。这篇文章可能对学习有好处,但是随着 OP 在另一篇文章中提供更多细节,可以为更高级别的问题提供更好的想法。
关于c - 如何在C程序中打印指针的地址值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309094/