PREV INDEX NEXT

Author: Stan Eisenstat
Subject: Re: [Cs223] returning an array
Date: Wednesday, 12 Feb 2020, 14:55:28


    > Message Posted By: Unknown
    >
    > usually we return an array in c using pointers. Since we can't use
    > pointers, and you said we didn't really need to use global variables, how
    > do return multiple values from a function? For example, if I want to use
    > one sorting algorithm in hw2 for both ffd and opt, I would have to return
    > a sorted array of items to be then used in either function.

Remember that when you pass an array to a function, you
can change the values stored in that array/ For example,
the following function will set the elements of its
array argument to 0:

  void zap (int X[], int n) {
      for (int i = 0; i < n; i++)
	  X[i] = 0;
  }

After the code snippet

  int n = 10;
  int A[n];
  zap (A, n);

the elements of the array A will all be 0.

Thus you can declare two arrays in main(), one for the
original set of values, the other for the sorted set.
The sort function sorts the values from the first array
into the second and then returns.  At this point the
second array contains the second set.  No globals or
(explicit) pointers are needed.

--Stan-
PREV INDEX NEXT