Reputation: 69
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)
Upvotes: 0
Views: 78
Reputation: 16824
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.
Upvotes: 4
Reputation:
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.
Upvotes: 1