可变函数 [英] Varadict functions
问题描述
我应该如何设置my_printf,以便它可以执行printf(%p")+而不使用printf的操作.
How should I set my_printf, so it would do what printf("%p") does + without using printf.
void my_printf(char * format, ...)
{
va_list ap;
va_start(ap, format);
if(!strcmp(format,"%p"))
{
void *address= va_arg (ap, void*);
char *arr=malloc(sizeof(address));
arr=address;
arr[strlen(arr)]='\0';
write(1,arr,strlen(arr));
}
va_end (ap);
//it has to print an address in hexadecimal format.
}
推荐答案
在:
char *arr=malloc(sizeof(address));
arr=address;
分配的块丢失,这是内存泄漏
the allocated block is lost, this is a memory leak
要做:
arr[strlen(arr)]='\0';
如果可以使用strlen
,则
没有意义,这意味着空字符已经存在.
但是完全不确定您是否有字符串,因此无法在该指针上使用strlen
.
您不知道是否可以出于很多原因对其进行修改,实际上这样做是没有用的.
has no sense, if you are able to use strlen
that means the null character is already present.
But it is not sure at all you have a string so you cannot use strlen
on that pointer.
You do not know if you can modify it for a lot of reasons, and in fact it is useless to do that.
在
write(1,arr,strlen(arr));
再次
假设您有一个字符串,这可能是错误的,并且您的目标不是写指向值的包含而是其地址.
again supposes you have a string, which can be wrong, and your goal is not to write the contain of the pointed value but its address.
一种方法是:
#include <stdint.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h> /* for malloc use in main */
void my_printf(char * format, ...)
{
va_list ap;
va_start(ap, format);
if (!strcmp(format,"%p"))
{
void * address= va_arg(ap, void*);
uintptr_t u = (uintptr_t) address;
if (u == 0)
fputs("(nil)", stdout);
else {
char s[2 * ((sizeof(u) * CHAR_BIT + 7) / 8) + 3];
int i = sizeof(s) - 1;
s[i] = 0;
do {
s[--i] = ((u & 0xf) < 10) ? ('0' + (u & 0xf)) : ('a' + (u & 0xf) - 10);
u >>= 4;
} while(u);
s[--i] = 'x'; /* can also putchar('0') */
s[--i] = '0'; /* can also putchar('x') */
fputs(s+i, stdout);
}
/* check */
printf("\n%p\n", address);
}
va_end (ap);
}
int main()
{
void * p = malloc(1);
my_printf("%p", 0);
my_printf("%p", &main);
my_printf("%p", &p);
my_printf("%p", p);
free(p);
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -Wall p.c
pi@raspberrypi:/tmp $ ./a.out
(nil)
(nil)
0x106b8
0x106b8
0xbec2d26c
0xbec2d26c
0x10b1558
0x10b1558
pi@raspberrypi:/tmp $
请注意,您的 printf 非常有限,只能管理简单的格式%p
Note your printf is very limited and only manage the simple format %p
这篇关于可变函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!