Thread: How to display the values of a struct

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    28

    How to display the values of a struct

    I have yet another question!

    How would you display the contents of struct?

    Code:
    typedef struct
    {
        char track[20];
        char trackname[20]; 
        char artist[20];
        char genre[20];
    }    song;
    E.G, in the code above, to printf the contents of trackname?

    A lecture provided:

    Code:
               int x;
    
               for(x=0; x<10; x++)
               printf("%d", a[x]);
    But I have little knowldege for adapting this. I tried changing the decimal into char and changing 'a[x]' into song, song.trackname and a few other variants, but have not been able to get it to work.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You display them the same way you display any other variable of the same type (the type you actually want to display; i.e.: an int, an array of char, etc.), you just prefix it with the structure instance:
    Code:
    printf( "foo.x = %d\n", foo.x );
    printf( "foo.arrayofchar = %s\n", foo.arrayofchar ); /* assuming it's actually a valid string */
    And so on...


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    28
    Thanks, quzah, but what are you referring to with 'foo'?

    I have tried entering those 'printf's in different way, but am unable to get them to work. I am very new to programming, so sorry if this seems really simple.

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Foo is just supposed to be replaced by the name of the instance of your struct.

  5. #5
    Registered User
    Join Date
    Feb 2010
    Posts
    28
    Thank you! This worked. I am really grateful

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help assignment due tomorrow
    By wildiv in forum C Programming
    Replies: 6
    Last Post: 01-27-2010, 08:38 PM
  2. Global Variables
    By Taka in forum C Programming
    Replies: 34
    Last Post: 11-02-2007, 03:25 AM
  3. Search Engine - Binary Search Tree
    By Gecko2099 in forum C Programming
    Replies: 9
    Last Post: 04-17-2005, 02:56 PM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM