0

I'm using this function to iterate any array:

void iterate(int len, int arr[], void (*pointer) (int, int) ) {
    for (int i = 0; i < len; ++i) {
        pointer(i, arr[i]);
    }
}

but in my inner function:

pointer(i, arr[i]);

I'm unable to modify arr[i] and assign it a new value. this is my code:

void iterate(int len, int arr[], void (*pointer) (int, int) ) {
    for (int i = 0; i < len; ++i) {
        pointer(i, arr[i]);
    }
}

void setCode(int index, int value) {
    cout << "[" << index << "]: ";
    cin >> value;
}

void showCode(int index, int value) {
    cout << index << " ---- " << value << endl;
}

int main() {

    int len;
    cout << "length: ";
    cin >> len;

    int code[len];

    void (*setCodePointer) (int, int) = setCode;
    void (*showCodePointer) (int, int) = showCode;

    iterate(len, code, setCodePointer);
    iterate(len, code, showCodePointer);
}

If I execute and set length to 2

position [0] to 1 and [1] to 2

I get:

0 ---- 1495894288 (should be 1)

1 ---- 32767 (should be 2)

duacos
  • 69
  • 11
  • 1
    You have the wrong signature for your function pointer. You are passing the 2nd int by value. If you modify the value it will not change the original array. – drescherjm Jun 01 '17 at 20:13
  • 2
    Either a typo or a duplicate of [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) – user4581301 Jun 01 '17 at 20:15

2 Answers2

4

Your function pointer signature

void (*pointer) (int, int)

is for a function which takes two integers by value, and returns nothing. This means that the function will receive copies of each of its arguments, and so any changes you make to the variables will be lost when the function ends.

Instead, you need to pass the second int parameter by reference, as in

void (*pointer) (int, int&)

and also change your setCode() and showCode() functions to match.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82
1

This int code[len]; isn't valid C++ (it is valid C99). And your set function doesn't work because you pass the thing you want to set by value, so the value you read is discarded and not stored in the array.