1

I have a problem with C++.

I have a function which sorts the array, but I don't want to work on an original array. I want to send the array to the function by value not by reference. Please help me.

int bogoSort(int tab[], int n){
int iloscOperacjiDominujacych = 0;
    cout<<"rozpoczalem algorytm BogoSort"<<endl;

    srand (time(NULL));
    named (outer)
    while(true){
 //       cout<<"Zaczal sie while"<<endl;
        named (inner)
        for(int i = 0; i < n; i++){
            if(i == n-1){
                break (outer);
            }
            if (tab[i] > tab[i+1]){
                break (inner);
            }
        }
        for(int i = n-1; i > 0; i--){
            iloscOperacjiDominujacych++;
            //operacja dominujaca to zamiana dwoch elementow w tablicy, wykonuje sie ZAWSZE najwiecej razy i jest najbardziej zlozona
            int swapPostition =  rand() % (i+1); //wylosowanie liczby miedzy <0;i> nalezacej do calkowitych
            int temp = tab[i];
            tab[i] = tab[swapPostition];
            tab[swapPostition] = temp;
        }
    }
//    cout<<"Wykonal sie while"<<endl;
    show(tab,n);
    return iloscOperacjiDominujacych;
}

3 Answers 3

8

There is no way to pass an array by value in C++. If you don't want to modify the original array, then you either have to make a separate copy yourself and manipulate the copy, or use std::vector or std::array (if you have C++11) and pass and return it by value (because you can copy std::vector or array).

2
  • How to effectively copy an Array(simple array not any collection)? Thanks for quick answer.
    – Yoda
    Apr 14, 2012 at 16:50
  • 1
    @RobertKilar make another array of the same size, use std::copy to copy the elements from the original array to the new one, and pass the copy into the function. Apr 14, 2012 at 16:51
4

C++ Says about function declarations

After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” [dcl.fct] 8.3.5/5

So when you want to pass an array C++ ends up passing a pointer to the first element of the original array, instead of making a copy and passing it by value as would be consistent with other types. This is an unfortunate consequence of C compatibility, and I have no idea why C thought this inconsistency was a good idea.

In any case, C++ offers std::array for statically sized arrays and std::vector for dynamically sized arrays. Because of the oddities with C arrays you should avoid them whenever possible. (There's rarely a situation where you can't avoid them)

int tab[] is an array with an unknown bound, so you can't use a statically sized std::array and must use std::vector:

int bogoSort(std::vector<int> tab){

Not that you no longer need the n parameter because the vector knows its own size. This is one of the ways std::vector and std::array are safer than an array. And even though a vector does have extra overhead associated with remembering that size, it's really zero overhead because it's saving you from having to do that work elsewhere.


If you really want to take a C array (which you should not) you can simply copy it manually.

int bogoSort(int const *tab,int n) {
    std::vector<int> tab_copy(tab,tab+n);
    bogoSort(tab_copy);
}

int bogoSort(std::vector<int> tab) {
    ...
}

As you can see, internally I'm using a vector and I have an overload of bogoSort that takes a vector. Compare this with making the copy a raw array:

int bogoSort(int const *tab,int n) {
  int *tab_copy = new int[n];
  std::copy(tab,tab+n,tab_copy);             // manual copying
  bogoSort_impl(tab_copy,n);                 // not overloading, hidden internal function
  delete [] tab_copy;                        // resource cleanup. We're not exception safe!
}

// or

int bogoSort(int const *tab,int n) {
  // unqiue_ptr for exception safety
  std::unqiue_ptr<int[]> tab_copy = std::unqiue_ptr<int[]>(new int[n]);
  std::copy(tab,tab+n,tab_copy.get());
  bogoSort_impl(tab_copy.get(),n);
}

So again, you really should not be using C arrays. They're too much trouble and there's no benefit.

3

You cannot pass C-style arrays by value. End of story.

You can however pass variables of class-type by value which contain arrays. The easiest way to exploit this is to use std::array:

void f(std::array<int, 10> a);

std::array<int, 10> a;
f(a);

The class is basically just something like struct { int data[10]; };, so you could even roll this yourself if you really wanted to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.