0
#include<iostream>

using namespace std;

class A{
        int *numbers[5];
        public:
            void assignment(int ** x){
                    for(int i=0;i<5;i++)
                            numbers[i]=x[i]; //not changing just the value of *numbers[i] but the pointer numbers[i]
            }
            void print(){
                    for(int i=0; i<5;i++)
                            cout<< *numbers[i]<<endl;
            }
};

int main(){
    int *x[5];
    for(int i; i<5;i++){
            x[i]= new int(i);
            cout<<*x[i]<<endl;
    }
    cout<<endl;
    A numbers;
    numbers.assignment(x);
    numbers.print();
    return 0;
}

My question is very specific. I want to do the same thing as the code above but instead of passing the argument of function assignment(int **) by pointer to do it by reference. How can I achieve that?

  • I am a bit puzzled by your question and the accepted answer. If you use`int *x[10];`, you can't use it as an argument to `assignment()`. Is that what you were hoping to accomplish? – R Sahu Dec 12 '14 at 18:27
  • Well, the question is just for educational purposes and it was asked in my confusion about passing by reference. For this specific example it answers my question as the whole question is about this specific segment of code and it works. It's true that what you are referring to would need something different from the chosen answer. Furthermore, what you said was also an issue for me and it got answered later. Thanks. – user234562 Dec 12 '14 at 19:39

1 Answers1

4

Use:

void assignment(int* (&x)[5]) ...

edit: for the comment "if the length... wasn't standard...", you can use a template:

template<int N> void assignment(int* (&x)[N]) ...

The compiler will automatically deduce N.

Zaskar
  • 569
  • 3
  • 10
  • Shouldn't this be `void assignment(const int* (&x)[5]) ...` for this case? – πάντα ῥεῖ Dec 12 '14 at 18:27
  • Awesome, thanks. If the length of the array wasn't standard(in this case 5) how would one go about that? – user234562 Dec 12 '14 at 18:34
  • πάντα ῥεῖ: no, because values will be stored in a no-const `int *[5]`... you could say `void assigment(int* const(&x)[5])` and make `x[i]` const, but `*numbers[i]` will be no-const. – Zaskar Dec 12 '14 at 19:22