Thread: Returning arrays from function to main

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    11

    Returning arrays from function to main

    I know that you can't simply return an array from a function to main but since I'm so confused on pointers, I need to ask for help.

    Here's basically a sketch of what I have:

    Code:
    int main (void)
    {
      int variable[3];
      variable = GetArray();
    }
    
    int GetArray(void)
    {
      int array[3];
    
      // do bunch of stuff here that fills the array
      return array[0];
    }
    I end up with bunch of big numbers if I try to print the array on main, but when I print the array in "GetArray" function, they come out as they are supposed to.

    How can I be able to do this successfully?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    11
    Thank you so much, that works well

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Originally posted by Salem
    Code:
    void getArray(int array[]);
    int main (void)
    {
      int variable[3];
      GetArray(variable);
      return 0;
    }
    
    void GetArray(int array[3])
    {
      // do bunch of stuff here that fills the array
    }
    Just curious. Is there a reason why you declared the array's size in the definition but not in the declaration of getArray?
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Is there a reason why you declared the array's size in the definition but not in the declaration of getArray?
    None at all - it makes no difference, but it should be consistent none the less.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  3. Returning arrays from a function.
    By Jaken Veina in forum C Programming
    Replies: 14
    Last Post: 03-21-2005, 06:07 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM