printf参数类型争吵 [英] printf parameter type wrangling
问题描述
我正在终端中打印结构成员表格,我希望
使用带有任意指针的printf,这样代码就更小了。
I不需要切换可能的类型。
但问题是 - 我可以传递任意类型(短,双,字符*,
等)printf作为char *(如果指定的格式字符串是
当然合适)?
我选择''char *''因为我推断它(一个指针)足够大
来容纳作为函数参数传递的任何原始类型。
#include< stdlib.h>
#include< stddef.h>
#include< stdio.h>
void
printf_member(void * obj,size_t off,const char * fmt)
{
char ** p;
p =(char **)((char *)obj + off);
printf(fmt,* p);
}
struct foo {
char c;
浮动f;
int i;
char * s;
};
int
main(无效)
{
struct foo f = {''c'',2.34 f,100,hello,world };
printf_member(& f,offsetof(struct foo,c)," [c] \ n");
printf_member(& ; f,offsetof(struct foo,f)," [%f] \ n");
printf_member(& f,offsetof(struct foo,i)," [%d ] \ n");
printf_member(& f,offsetof(struct foo,s)," [%s] \ n");
返回0;
}
不幸的是,这种技术似乎不能作为浮动成员使用
未打印正常。为什么?
$ gcc -Wall -W -ansi -pedantic -o pa pa.c
$ ./pa
[c]
[0.000000]
[100]
[你好,世界]
谢谢,
迈克
I''m printing tables of structure members in a terminal and I would like
to use printf with an arbitrary pointer so that the code is smaller and
I don''t need to switch over ever possible type.
But the question is - can I pass an arbitrary type (short, double, char *,
etc) to printf cast as a char * (provided the specified format string is
appropriate of course)?
I chose ''char *'' because I reasoned it (a pointer) would large enough
to accommodate any primitive type passed as a function parameter.
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
void
printf_member(void *obj, size_t off, const char *fmt)
{
char **p;
p = (char **)((char *)obj + off);
printf(fmt, *p);
}
struct foo {
char c;
float f;
int i;
char *s;
};
int
main(void)
{
struct foo f = { ''c'', 2.34f, 100, "hello, world" };
printf_member(&f, offsetof(struct foo, c), "[c]\n");
printf_member(&f, offsetof(struct foo, f), "[%f]\n");
printf_member(&f, offsetof(struct foo, i), "[%d]\n");
printf_member(&f, offsetof(struct foo, s), "[%s]\n");
return 0;
}
Unfortunately this technique does not appear to work as the float member
was not printed properly. Why?
$ gcc -Wall -W -ansi -pedantic -o pa pa.c
$ ./pa
[c]
[0.000000]
[100]
[hello, world]
Thanks,
Mike
推荐答案
gcc -Wall -W -ansi -pedantic -o pa pa。 c
gcc -Wall -W -ansi -pedantic -o pa pa.c
./ pa
[c]
[0.000000]
[ 100]
[你好,世界]
谢谢,
迈克
./pa
[c]
[0.000000]
[100]
[hello, world]
Thanks,
Mike
Michael B Allen在21/08/05写道:
Michael B Allen wrote on 21/08/05 :
我正在终端打印结构成员表,我想
使用printf一个任意指针,使代码更小,
I''m printing tables of structure members in a terminal and I would like
to use printf with an arbitrary pointer so that the code is smaller and
这篇关于printf参数类型争吵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!