Thread: Passing an Array to a function

  1. #1
    Registered User
    Join Date
    Jun 2007

    Passing an Array to a function


    just so you know, I'm still learning the basics of C.

    I've started creating functions and passing one parameter at a time to them. Like one integer or one string. My question is how do you pass an array of integers to a function, manipulate them, and then send them back to the main routine?

    Any examples of code or any links to descriptions would be very appreciated.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Well strings are arrays of characters.

    So when you say
    char foo[ ] = "hello";
    strlen( foo );

    If you look up strlen, you'll see it takes a char* pointer.

    An identical call would be
    strlen( &foo[0] );

    Also, since arrays are always passed as a pointer, whatever you do to the array inside the function (via the pointer), the effect will be stored in the array declared by the caller.
    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
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    You don't pass the whole array to a function. You pass a pointer to the first element in the array to the function. Try something like this:
    void func(int nums[10])
      int i;
      for(i = 0;i < 10;++i)
        nums[i] = i;
    int main(void)
      int i;
      int nums[10];
      func(nums);  // An equivalent call would be func(&nums[0]);
      for(i = 0;i < 10;++i)
        printf("&#37;d\n", nums[i]);
      return 0;
    The parameter in func() can actually be expressed in different ways, and the size of the last dimension can actually be omitted. These definitions would all work:
    void func(int nums[10])
    void func(int nums[])
    void func(int *nums)
    Since you're passing a pointer to the first element in the array, your function doesn't have its own local copy of the array. Any changes you make to the array in your function are reflected in the calling function.
    Last edited by itsme86; 06-19-2007 at 01:32 PM.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Replies: 7
    Last Post: 11-21-2008, 04:27 PM
  3. function passing argument..array ?
    By jochen in forum C Programming
    Replies: 2
    Last Post: 09-30-2007, 11:53 AM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM