0

So I understand the basics of Array functions, but I am having trouble converting this source code from an array function to a function using pointers.

void sortArray(int array[], int size)
{
  bool swap;
  int temp; 
  do
  {
    swap = false;
    for (int count = 0; count < (size - 1); count++)
      {
        if (array[count] > array[count + 1])
        {
          temp = array[count];
          array[count] = array[count + 1];
          array[count + 1] = temp;
          swap = true;
        }
      }
    } while (swap);
}
El Spiffy
  • 135
  • 5
  • `void sortArray(int* array, int size)`? Check out this [tutorial](http://www.tutorialspoint.com/cplusplus/cpp_passing_arrays_to_functions.htm). – Mohamad Elghawi Nov 24 '15 at 10:22
  • 1
    That *is* a function using pointers. In function parameters, `T x[]` is equivalent to `T* x`. – molbdnilo Nov 24 '15 at 10:22

1 Answers1

0

This function already can work with pointers.

Definition:

void sortArray(int array[], int size)

Is equivalent to:

void sortArray(int* array, int size)
Alex
  • 9,891
  • 11
  • 53
  • 87
  • just curious if your prototype is like `void sortArray(int array[], int size);` and you have a variable.. `int *arr = new int[size];` and you call the func `sortArray(arr,size);` will the array be passed by ref or copy – Minato Nov 24 '15 at 10:25
  • @Minato Look this question: http://stackoverflow.com/questions/4774456/pass-an-array-to-a-function-by-value – Alex Nov 24 '15 at 10:27
  • By doing that I will change the parameters of the function, does that mean I must also chance the elements of the function (i.e from array[count] to *array[count]? – El Spiffy Nov 24 '15 at 10:34
  • 1
    @ElSpiffy no.. you can use the pointer provided as a normal array – Minato Nov 24 '15 at 10:35
  • If that is true then why am I being asked to create a bubble sort using pointer algorithms? I mean, it makes sense that they are equivalent. But is there a difference from array bubble sort and pointer bubble sort? – El Spiffy Nov 24 '15 at 10:35
  • @ElSpiffy Arrays are passed as base address between functions.. that said.. when you declare it like above it is expecting an address.. since array are contagious memory.. you just increment the base address to retrieve the next element.. – Minato Nov 24 '15 at 10:37
  • @ElSpiffy, If you want to show, that you are using pointers, you can replace `array[i]` to `*(array + i)`, but it will not change the assembler code because both of these variants are totally equivalent. – Alex Nov 24 '15 at 10:39