Click to See Complete Forum and Search --> : Function Pointer
vcstarter
July 18th, 2002, 01:21 PM
I do have a function pointer. See the code below. I thought it is unecessary to define the variable as the return value. What can I do to make it better. For example, let the function return itself, which is impossible to my knowledge. For examjple,
return add number
or return (*x + y) something like that
how can I do that
#include <iostream.h>
#include <conio.h>
int *AddNumber(int *x, int *y)
{
int i;
int *z;
const int k=5;
for (i=0;i<k;i++)
{
z[i] = x[i] + y[i];
}
return z;
}
void main()
{
int x[5] = {0,2,4,6,8};
int y[5] = {1,2,3,4,5};
int i, *z;
z = AddNumber(x,y);
for (i=0;i<5;i++)
{
cout<<z[i];
cout<<endl;
}
getch();
}
arunkumar_gona
July 18th, 2002, 03:00 PM
AddNumber is a function which returns a pointer to an integer, it is not a function pointer.
You will have to allocate memory for z before using it.
int *z = new int[k];
deallocate the memory after you are done with it.
either you can return the result the way you are doing or you can pass a reference to the variable as an argument.
vcstarter
July 18th, 2002, 03:11 PM
how can I return the function pointer by itself without using any other variable to wast memory space. If it is not possible, I don't see any reason of using a fucntion that point to a pointer, exept declare another variable to use the same memory space. This is ony the advantage I have seen so far.
cup
July 19th, 2002, 05:46 AM
I think you are mixing up function pointers and functions that return pointers. What you have is a function that returns a pointer. As arunkumar_gona says, you need to create some space to return the result. The pointer to that space is then returned by your function and you are responsible for deleting it.
An alternative strategy is to create a void function and pass in z.
For an example of a function pointer, have a look at the qsort definition. You have to create a function that returns -1, 0 or 1 depending on which way you want the comparison to go. The address of this function is then passed to the qsort routine. That is an example of the usage of a function pointer.
Function pointers are extremely useful for state machines.
In C++, this has largely been replaced by inheritence. In Java, you can only use inheritence: there are no function pointers.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.