M
Michael B Allen
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
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