CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2002
    Posts
    936

    Function Pointer

    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();

    }

  2. #2
    Join Date
    Mar 2000
    Location
    Seattle , WA
    Posts
    87
    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.

  3. #3
    Join Date
    Jun 2002
    Posts
    936
    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.

  4. #4
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,020
    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.
    Succinct is verbose for terse

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured