Thread: pointers to functions

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    13

    subject

    i need an array of pointers to functions that can be set to a variable size.

    Code:
    void (*functions[3])(void*,void*); //works, but not what i'm looking for
    
    void (*functions[vSize])(void*,void*); //doesnt work (expected constant expression)
    
    void (**functions)(void*,void*); //can't allocate later, because new constant won't work with void objects
    is it possible? or will i have to just set it to a constant size...

  2. #2
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    Maybe like this?
    Code:
    #include <iostream>
    
    typedef void (*pFunc)(void);
    
    void someFunc(pFunc* fcnArray, int size)
    {
      for (int i=0;i<size;i++)
        fcnArray[i]();
    }
    
    void Fcn1()
    {
      std::cout<<"Function 1!"<<std::endl;
    }
    void Fcn2()
    {
      std::cout<<"Function 2!"<<std::endl;
    }
    void Fcn3()
    {
      std::cout<<"Function 3!"<<std::endl;
    }
    int main()
    {
    pFunc myFcnArray[3];
    myFcnArray[0] = Fcn1;
    myFcnArray[1] = Fcn2;
    myFcnArray[2] = Fcn3;
    someFunc(myFcnArray,3);
    }
    Typdefs make function pointers easier

    And check out function-pointer.org
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Code:
    #include <iostream>
    using namespace std;
    
    typedef void(*pfunc)(int);
    
    void func1(int num)
    {
    	cout<<"func1: "<<num<<endl;
    }
    
    void func2(int num)
    {
    	cout<<"func2: "<<num<<endl;
    }
    
    void func3(int num)
    {
    	cout<<"func3: "<<num<<endl;
    }
    
    int main()
    {
    	pfunc MyFunctions[3] = {func1, func2, func3};
    	
    	int size = 0;
    	cout<<"Input the array size: ";
    	cin>>size;
    
    	pfunc* funcArray = new pfunc[size];
    	for(int i=0; i<size; i++)
    	{
    		funcArray[i] = MyFunctions[i];
    	}
    
    	for(int j=0; j<size; j++)
    	{
    		funcArray[j](j * 10);
    	}
    
    		
    	delete [] funcArray;
    
    	return 0;
    }
    Last edited by 7stud; 10-18-2005 at 12:33 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Conversion of pointers to functions
    By hzmonte in forum C Programming
    Replies: 0
    Last Post: 01-20-2009, 01:56 AM
  2. HELP WITH FUNCTIONS and POINTERS!!!
    By cjohnson412 in forum C++ Programming
    Replies: 4
    Last Post: 08-11-2008, 10:48 PM
  3. Replies: 4
    Last Post: 11-23-2003, 07:15 AM
  4. pointers, functions, parameters
    By sballew in forum C Programming
    Replies: 3
    Last Post: 11-11-2001, 10:33 PM