Thread: Is it possible to print a struct to stdout?

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485

    Is it possible to print a struct to stdout?

    Is it possible to display a struct in stdout in one go? Letīs say you got a struct with different data types, it would be convenient to be able to print to stdout reffering only to the struct, not the individual members.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,674
    Short answer is no.

    If you're using gcc with the GNU LibC, then you can hook in your own printf format styles, but you might be pushing your luck with structs.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Thanks Salem. I am using gcc but I think Iīm going to take no for an answer, for now at least.

  4. #4
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    You can at least print struct as chars. Do a print function which takes structs size ptr to struct as void ptr.

    Then just print the values in structs as chars in hexa format (in loop). When you know what struct you printed, you can quite easily calculate the values of independent members later. Just remember that if you do not have used any packing pragmas, compilers often add padding to keep default (usually 32 bit) alignation (or how do you say that).

  5. #5
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Maz, thatīs an interesting approach. Iīll look into it.

    Cheers.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,653
    Quote Originally Posted by Maz View Post
    You can at least print struct as chars. Do a print function which takes structs size ptr to struct as void ptr.

    Then just print the values in structs as chars in hexa format (in loop). When you know what struct you printed, you can quite easily calculate the values of independent members later. Just remember that if you do not have used any packing pragmas, compilers often add padding to keep default (usually 32 bit) alignation (or how do you say that).
    That is not a very good solution... it gives pretty much some "non-sensical" output since all the data would be printed as hexa-decimal and it's not immediately obvious (perhaps ever?) what they are.

    Quote Originally Posted by Subsonics View Post
    Is it possible to display a struct in stdout in one go? Letīs say you got a struct with different data types, it would be convenient to be able to print to stdout reffering only to the struct, not the individual members.
    I suppose not, but you could write a custom function to output the data. Then all it would take is a single line to call the function.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    No doubt I'm stating the obvious, but you can always wrap your struct-displaying code into one function.
    Code:
    struct person {
        char *age;
        int name;
    };
    
    void print_person(struct person who) {
        printf("%s, age %d", who->name, who->age);
    }
    
    struct person joe;
    
    joe.name = malloc(10);
    strcpy(joe.name, "Joe");
    
    joe.age = 33;
    
    print_person(joe);
    printf("\n");
    In C++, you can overload the << operator for your data type, but of course this isn't possible in C.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,653
    Quote Originally Posted by dwks View Post
    No doubt I'm stating the obvious, but you can always wrap your struct-displaying code into one function.
    Yeah, that's what I mentioned
    Not to mention you never free the memory (I know I'm picky )!
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Quote Originally Posted by Elysia View Post
    ..you could write a custom function to output the data. Then all it would take is a single line to call the function.
    I have been trying that, but never successfully :-D. I was not sure how I should interpret that it was not possible, started to fear that making a print function was out of the question.

    This is what I have come up with so far.

    main:
    Code:
    	typedef struct {
    		int foo;
    		char name[25];		
    	} Test;
    	
    	Test myTest;
    	int *pt = NULL;
    	
    	myTest.foo = 100;
    	myTest.name[0] = 'F';
    	myTest.name[1] = 'r';
    	myTest.name[2] = 'e';
    	myTest.name[3] = 'd';
    	
    	printStruct(&myTest.foo);
    printStruct:
    Code:
    int printStruct(int *first) {
    	int foo;
    	char name[25];
    	
    	foo = *first;
    	printf("Foo: %d\n", foo);
    	first++;
    	name[0] = (char)*first;
    	printf("Name: %s\n", name);
    	
    	return 0;
    }
    This outputs the int correctly but only the last letter of name.


    dwks,

    Some of that code looks a bit forreign to me still, what is the -> operator doing?

    Thanks guys!

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,653
    Code:
    typedef struct
    {
        int foo;
        char name[25];		
    } Test;
    	
    int main()
    {
        Test myTest;
    	
        myTest.foo = 100;
        strcpy(myTest.name, "Fred");
    	
        printStruct(&myTest);
    }
    
    void printStruct(Test* pTest)
    {
        printf("Foo: %d\n", pTest->foo);
        printf("Name: %s\n", pTest->name);
    }
    pTest->foo is the same as (*pTest).foo.
    You were making this much harder than it needs be. I'm guessing you haven't learned all that much about C, yet.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Elysia, thats great!

    Quote Originally Posted by Elysia View Post
    I'm guessing you haven't learned all that much about C, yet.
    True, learning as we speak. Thanks.

  12. #12
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    Quote Originally Posted by Elysia View Post
    That is not a very good solution... it gives pretty much some "non-sensical" output since all the data would be printed as hexa-decimal and it's not immediately obvious (perhaps ever?) what they are.


    I suppose not, but you could write a custom function to output the data. Then all it would take is a single line to call the function.
    So you suggest writing own print function for each struct?

    And when you print the memory occupied by struct - char by char in hexa format, it is pretty easy to see what's stored in a struct (as long as we remember endianess issues and padding). I wonder where have you got the impression reading hexa is hard???

    Another option is to use #ifdefs and and create debug structs which contain the size of struct as first member, and then type of members in struct. That way one could print whole struct's contents in more easily read format, and disable these prints after debug stage is over - with only one function, no matter how many different structs there is.

  13. #13
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,786
    I wonder where have you got the impression reading hexa is hard???
    I never could restore the float value looking at its hex representation...
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  14. #14
    and the hat of copycat stevesmithx's Avatar
    Join Date
    Sep 2007
    Posts
    587
    And when you print the memory occupied by struct - char by char in hexa format, it is pretty easy to see what's stored in a struct (as long as we remember endianess issues and padding).
    Interesting. Can you give an example to illustrate your point?
    Not everything that can be counted counts, and not everything that counts can be counted
    - Albert Einstein.


    No programming language is perfect. There is not even a single best language; there are only languages well suited or perhaps poorly suited for particular purposes.
    - Herbert Mayer

  15. #15
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194

    Wink

    Allright peeps. I did not mean to start a war (here too)
    And I admitt I forgot the floats and doubles, they're harder. It has been long since I last needed floats or doubles. But I am positive that with a decent amount of searching, you can find out how they're represented, and when you convert hexas to binary, take your calculator and spend some time more, you'll eventually have those solved too

    simple non tested, straight to post coded example:

    Code:
    void print_struct( void *struct, size_t structSize)
    {
        size_t i;
        char *printme=(char *)struct;
        int formatter=1;
        for( i=0;i < structSize;i++ )
        {
             printf("%02x ",*printme++):
             if(!(formatter%4))
             {
                  printf("\n");
             }
        }
    }
    example:

    typedef struct foo
    {
    int first;
    char second;
    char third;
    char fourth;
    void *fifth;
    }foo;

    print might produce:
    A1 00 00 00
    4D 61 7A 00
    00 00 00 00

    Now we can analyze this,
    Knowing I am using PC in 32 bit arch, I know addresses are 32 bit wide, and it uses little endian arch. So let's see.
    first 4 bytes (first row) is the int's value. Little endian system, so least significant bytes are first, EG int is A1 in hexa, which is 161 in ints. Then tehre's 3 chars, Eg chars 4D 61 7A. Quick look at ASCII table says, it is Maz.
    The last 00 in that row is pretty likely to be the padding, to maintain default 32 bit alignation.
    Last is void pointer, and as we see it is pointing at NULL address.

    What was the hard part?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with linked list sorting function
    By Jaggid1x in forum C Programming
    Replies: 6
    Last Post: 06-02-2009, 02:14 AM
  2. Global Variables
    By Taka in forum C Programming
    Replies: 34
    Last Post: 11-02-2007, 03:25 AM
  3. What's wrong with my search program?
    By sherwi in forum C Programming
    Replies: 5
    Last Post: 04-28-2006, 09:57 AM
  4. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM