如何在不使用printf的情况下打印指针地址 [英] How to print a pointer address without printf
本文介绍了如何在不使用printf的情况下打印指针地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个练习,其中需要打印指针的内存(地址).用printf("%p", ..)
可以很容易地做到这一点,但是我不允许使用它.
I'm doing an exercise in which I need to print the memory (address) of a pointer. It would be easy to do it with printf("%p", ..)
but I'm not allowed to use it.
您知道不使用printf()
就可以获取地址吗?
我唯一可以使用的功能是写".
Do you know how I can get the address without using printf()
?
The only function I can use is 'write'.
这是我的运动说明:
编写一个函数,该函数采用(const void *addr, size_t size)
,并显示
如示例中所示的内存.
您的函数必须声明如下:
Write a function that takes (const void *addr, size_t size)
, and displays the
memory as in the example.
Your function must be declared as follows:
void print_memory(const void *addr, size_t size);
$ cat main.c
void print_memory(const void *addr, size_t size);
int main(void)
{
int tab[10] = {0, 23, 150, 255,
12, 16, 21, 42};
print_memory(tab, sizeof(tab));
return (0);
}
$ gcc -Wall -Wall -Werror main.c print_memory.c && ./a.out | cat -e
0000 0000 1700 0000 9600 0000 ff00 0000 ................$
0c00 0000 1000 0000 1500 0000 2a00 0000 ............*...$
0000 0000 0000 0000 ........$
推荐答案
您可以尝试:
#include <stdio.h>
void print_memory(const void *addr, size_t size)
{
size_t printed = 0;
size_t i;
const unsigned char* pc = addr;
for (i=0; i<size; ++i)
{
int g;
g = (*(pc+i) >> 4) & 0xf;
g += g >= 10 ? 'a'-10 : '0';
putchar(g);
printed++;
g = *(pc+i) & 0xf;
g += g >= 10 ? 'a'-10 : '0';
putchar(g);
printed++;
if (printed % 32 == 0) putchar('\n');
else if (printed % 4 == 0) putchar(' ');
}
}
int main(void) {
int tab[10] = {0, 23, 150, 255, 12, 16, 21, 42};
print_memory(tab, sizeof(tab)); return (0);
return 0;
}
输出
0000 0000 1700 0000 9600 0000 ff00 0000
0c00 0000 1000 0000 1500 0000 2a00 0000
0000 0000 0000 0000
这篇关于如何在不使用printf的情况下打印指针地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文