Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Passing Arrays to Functions

You can also pass arrays to functions. For instance, the following example adds the elements of an array and returns the sum:

  int data[] = {1, 2, 3, 4};

  int total = adder(data,
    sizeof(data)/sizeof(int));

  printf("The total is %i\n", total);

long adder(int array[], int number_
elements)
{
  long sum = 0;
  int loop_index;

  for (loop_index = 0; loop_index <
    number_elements; loop_index++)
      sum = sum + array[loop_index];

  return sum;
}

To pass arrays to functions:

  1. Create a new program named functionpassarrays.m.
  2. In functionpassarrays.m, enter the code shown in Listing 4.13.

    This code creates an array and passes it to a function named adder().

    Listing 4.13. Starting functionpassarrays.m.

    #include <stdio.h>
    
    long adder(int array[], int number_elements);
    
    int main()
    {
      int data[] = {1, 2, 3, 4};
    
      int total = adder(data,
        sizeof(data)/sizeof(int));
    
      printf("The total is %i\n", total);
    
      return 0;
    }

    Listing 4.14. The functionpassarrays.m program.

    #include <stdio.h>
    
    long adder(int array[], int number_elements);
    
    int main()
    {
      int data[] = {1, 2, 3, 4};
    
      int total = adder(data,
        sizeof(data)/sizeof(int));
    
      printf("The total is %i\n", total);
    
      return 0;
    }
    
    long adder(int array[], int number_elements)
    {
      long sum = 0;
      int loop_index;
    
      for (loop_index = 0; loop_index <
        number_elements; loop_index++)
          sum = sum + array[loop_index];
    
      return sum;
    }
  3. Add the code to create the adder() function (Listing 4.14).
  4. Save functionpassarrays.m.
  5. Run the functionpassarrays.m program.

    You should see the following:

    The total is 10
  • + Share This
  • 🔖 Save To Your Account