Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf for struct? (C/C++, VC2008)

Just build&run this in VC2008:

struct A
{
   int a;
   int b;
   int c;
};
A a = { 10, 20, 30 };
printf("%d %d %d\n", a);

Is it normal?

10 20 30

I'd like to cast! but it don't works:

struct A
{
   int a;
   int b;
   int c;
   operator int()
   {
      return a + b + c;
   }
};
A a = { 10, 20, 30 };
printf("%d\n", a);

output is only:

10

I need auto-casting for template-utility. Here it is: https://code.google.com/p/boolib/source/browse/boolib/crypt/ShakedValue.h It should hide in memory value, that any hack-programms (ArtMoney) can't find value.

And one more trick usage: Print private members of the struct/class

like image 764
k06a Avatar asked Nov 02 '10 19:11

k06a


People also ask

Can I print a struct in C?

C/C++ does not support to print out struct's field name. This is a guide showing how to print struct field and value using macros.

How do you print the address of a struct in C?

In C, we can get the memory address of any variable or member field (of struct). To do so, we use the address of (&) operator, the %p specifier to print it and a casting of (void*) on the address.

What does %% mean in printf?

Save this answer. Show activity on this post. % indicates a format escape sequence used for formatting the variables passed to printf() . So you have to escape it to print the % character.


1 Answers

If you want a cast, then cast it:

struct A
{
   int a;
   int b;
   int c;
   operator int()
   {
      return a + b + c;
   }
};
A a = { 10, 20, 30 };
printf("%d\n", (int)a);

the output will be

60
like image 177
Blindy Avatar answered Sep 24 '22 20:09

Blindy