Tuesday, February 7, 2017

Dynamic Array of Function Pointers

Develop a program that creates a dynamic array of function pointers that return void and takes an integer parameter. It will then initialize the array with values as addresses of f1, f2, f3 in sequence. It will also, produce a call sequence array and shuffle it 100 time and then pass these two arrays to a function that will call the functions in the first array according to the sequence in the second array, which terminates with an -1 terminator.
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <algorithm>

using namespace std;

void f1(int n)
{
    cout << "I am f1\n";
}
void f2(int n)
{
    cout << "I am f2\n";
}
void f3(int n)
{
    cout << "I am f3\n";
}





//creates a typedef void pointer function that returns int
typedef void (*funtPointer)( int );

//The following array will  shuffle the elements inside the array when it gets called
void arrayshuffle(int shuffle[], int sizeofArray)
{

    srand((unsigned)time(0));
    for(int x=0; x<100; x++)
        random_shuffle(&shuffle[0],&shuffle[sizeofArray]);
};

// Will call function depending on the array sequence
void callFunctions(funtPointer* mArray, int arraySequence[])
{
    int i=0;
      while(arraySequence[i] != -1)
    {
        (*(mArray[arraySequence[i]]))(i);
        i++;
    }
}

int main()
{
    int aSeq=0;
    //running condition
    while(aSeq != -1)
    {





        funtPointer* t_array;
        t_array = new funtPointer[3];
        t_array[0] = &f1;
        t_array[1] = &f2;
        t_array[2] = &f3;
        cout << "Please: Enter the number of sequences!!!\n";
        cin >> aSeq;
        if(aSeq!=-1)
        {
            int *arraySequence = new int[aSeq];
            for (int i = 0; i < aSeq - 1; i=i+3)
            {
                arraySequence[i] = 0;
                arraySequence[i+1] = 1;
                arraySequence[i+2] = 2;
            }
            arraySequence[aSeq] = -1;
            //Calling the shuffle function
            arrayshuffle(arraySequence,aSeq);
            //Calling the display function
            callFunctions(t_array, arraySequence);
            // delete the array so that new numbers can be entered
            delete[]arraySequence;
        }
        //delete the pointer array
        delete[]t_array;
    }
    return 0;
}





No comments:

Post a Comment