C++ Function Pointer Array Question

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using namespace std;

const int * fun1(int *,int);
const int * fun2(int *,int);

const int * fun1(int * x, int y){ 
	for(int i = 0;i < 5; i++)
		x[i] += y;
	return x;
}
const int * fun2(int * x, int y){
	for(int i = 0;i < 5; i++)
		x[i] -= y;
	return x;
}

int main(){

	const int *(*ptr[2])(int *,int) = {fun1, fun2};
		
	int ary[] = {1,2,3,4,5};
		
	cout << "fun1 :" << endl;
	for(int i = 0 ; i < 5 ; i++){
		cout <<*(*ptr[0])(ary,1)<<",";
	}
	
	cout << "\nfun2 :" << endl;
	for(int i = 0 ; i < 5 ; i++){ // I dont know why the output was reversed
		cout <<*(*ptr[1])(ary,1)<<",";
	}
	
	return 0;
}



fun1 :
2,3,4,5,6,
fun2 :
5,4,3,2,1,
You are only showing the first element in the array because you return the array whilst immediately dereferencing it, this is the same as [0].

So in your case, you count from 1 to 6, then from 6 to 1 again.
You effectively print *ary, i.e. ary[0] every time, don't you?
Last edited on
Thx a lot /_\ ,I think i have asked a stupid question
Because you are subtracting on line 15 instead of adding like you did on line 10.

You are not actually printing out your array. You are printing out the first element of your array in a loop.

Try this:

25
26
27
28
29
	cout << "fun1 :" << endl;
	(*ptr[0])(ary,1);
	for(int i = 0 ; i < 5 ; i++){
		cout << ary[i] << ",";
	}

Hope this helps.
i have same Question for asking so thanks to everyone....
Thx u guys
Topic archived. No new replies allowed.