Thread: How to pass a structure to a function

  1. #1
    Registered User zolfaghar's Avatar
    Join Date
    Mar 2016
    Posts
    95

    How to pass a structure to a function

    I have the following code ...

    Code:
    #include <stdio.h>
    int main (void)
    {
    struct book
      {
        char name[25];
        char author [25];
        int callno;
      };
    struct book b1 = { "Moubidick", "Ansari,Shahin", 101};
    display (b1);
    }
    display (struct book b)
    {
      printf ("\n Here is the book information %s %s %d", b.name, b.author, b.callno);
    }
    ~
    Code:
    And I get the following warnings: 
    
    struct3.c:14:17: warning: 'struct book' declared inside parameter list
     display (struct book b)
                     ^
    struct3.c:14:17: warning: its scope is only this definition or declaration, which is probably not what you want
    struct3.c:14:22: error: parameter 1 ('b') has incomplete type
     display (struct book b)
                          ^
    I looked around online, and I believe the warnings are for not declaring the variable b earlier in the main. Is that right?
    I like to know if what I am doing is the best way to go about passing a structure to a function. It is not my code; I am following a text and it may be that the author is trying to teach something, which he'll build on later.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    You declared your struct inside your main function. Display has no way to know of its existence. Move your struct declaration to somewhere both main and display can see it, as a first step.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  3. #3
    Registered User zolfaghar's Avatar
    Join Date
    Mar 2016
    Posts
    95
    Thanks. It compiled without error.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. structure pass by reference
    By Yifangt in forum C Programming
    Replies: 17
    Last Post: 04-20-2016, 09:53 AM
  2. is it possible to pass a structure element by reference?
    By Cathalo in forum C++ Programming
    Replies: 6
    Last Post: 03-04-2009, 10:01 AM
  3. Pass structure by reference(?)
    By azerej in forum C Programming
    Replies: 4
    Last Post: 05-22-2008, 02:10 AM
  4. pass structure to function
    By tat in forum C Programming
    Replies: 18
    Last Post: 12-06-2007, 08:01 PM
  5. Structure pass-by-reference - help?
    By dxfoo in forum C Programming
    Replies: 28
    Last Post: 08-20-2005, 10:16 PM

Tags for this Thread