Thread: function returning pointer

  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    92

    Lightbulb function returning pointer

    Code:
    #include<stdio.h>
    int* func(int x);
    int c[5]={9,6,7,8};
    int main()
    {
    int a[5]={1,2,3,4};
    int *p;
    p = func(a[0]);
    printf("%d",p[1]);
    }
    
    int* func(int x)
    {
     int* b = new int[5];
     if((x==c[0]||x==c[1]))
     {b[0]=10;}
      else
     {
     b[0]=25;
     b[1]=20;
     b[2]=69;
     }
     return b;
     delete b;  //  can i place delete here ?
    }
    question
    ------------

    this code is working. but how do i know how many elements are actually returned by the ponter b ?

    in fact here 3 elements(i.e b[0],b[1],b[2]) are returned in the above code.

    how does the caller know how many is returned so that he could print all the returned elements.
    Last edited by blue_gene; 04-19-2004 at 01:46 PM.
    blue_gene

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >this code is working.
    My compiler disagrees.

    >how does the caller know how many is returned so that he could print all the returned elements.
    Use an extra pointer argument to the function that saves the number of elements.

    >delete b; // can i place delete here ?
    Not in C.
    My best code is written with the delete key.

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>how does the caller know
    It doesn't

    >>int* b = new int[5];
    Please don't post C++ on the C forum. There's a C++ forum over here

    >> return b;
    >>delete b;
    The delete will never run, which is actually a good thing as you've just returned the pointer to the caller for their use.

    Try something like this:
    Code:
     #include <stdio.h>
     #include <stdlib.h>
     
     int foo(int **i)
     {
       *i = malloc(sizeof(**i) * 10);
       
       if (*i)
         return (10);
       else
         return 0;
     }
     
     int main(void)
     {
       int *p;
       int i;
       
       i = foo(&p);
       
       if (i)
       {
         printf ("Space for %d ints malloc'ed\n", i);
         free (p);
       }
       
       return(0);
     }
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Registered User
    Join Date
    Dec 2003
    Posts
    92
    >My compiler disagrees

    i am using g++...it works. i printed p[0],p[1] ,..its giving result 25,20 respectively.


    >Use an extra pointer argument to the function that saves the number of elements.

    do u suggest to return a structure ?

    is there no easy way?


    sorry Hammer...for using new , delete in C code. i dislike malloc. new delete are compact and comfortable.

    anyway assume that is a C code only. i wanted to print all the returned elements in my code.

    something like below.....

    for(int m=0;m<no_of_returned_elements;m++)
    printf("%d",p[m]);


    how can achieve my goal ?
    blue_gene

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >i am using g++...it works.
    I'm compiling as C...it most certainly doesn't work.

    >how can achieve my goal ?
    This is what I meant:
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    int* func(int x, int *n);
    int c[5]={9,6,7,8};
    int main()
    {
      int a[5]={1,2,3,4};
      int *p;
      int m, n;
      p = func(a[0],&n);
      for(m=0;m<n;m++)
        printf("%d ",p[m]);
    }
    
    int* func(int x, int *n)
    {
      int* b = malloc(5 * sizeof *b);
      if((x==c[0]||x==c[1]))
      {
        b[0]=10;
        *n = 1;
      }
      else
      {
        b[0]=25;
        b[1]=20;
        b[2]=69;
        *n = 3;
      }
      return b;
    }
    But a structure will work too.
    My best code is written with the delete key.

  6. #6
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    The number of elements used could either be passed as a parameter to the function (in the form of a pointer, of course), or you could use a sentinel value to mark the end of the array (just as strings are zero-terminated).

    >> return b;
    >> delete b;

    Anything that appears after a return statement will not get executed. Second, you shouldn't delete the memory from within the function since it is being used afterward! Instead, either return the dynamic memory to the caller, and let the caller clean it up later (not recommended), or just create the array from the callers scope and pass it as a parameter to the function.

    Another thing I noticed was that the function references a global variable. This is almost always a very bad idea. A much better way would be to pass the variable as a parameter.

    Code:
    #include<stdio.h>
    
    int * func(
     int param, 
     int dest[], 
     int src[], 
     int max_elements, 
     int * used);
    
    int c[5]={9,6,7,8};
    
    int main()
    {
     int a[5]={1,2,3,4};
     int b[5];
     int *p;
     int total;
    
     p = func(a[0], b, c, 5, &total);
    
     printf("%d",p[1]);
    
     return 0;
    }
    
    int * func(
     int param, 
     int dest[], 
     int src[], 
     int max_elements, 
     int * used)
    {
      *used = 0;
    
             if((param==src[0]||param==src[1]))
            {
                if(max_elements >= 1)
               { 
                dest[0]=10; 
                *used = 1; 
               }
            }
             else 
           {
                if(max_elements >= 3)
               {
                dest[0]=25;
                dest[1]=20;
                dest[2]=69;
                *used = 3;
               }
           }
    
     return dest;
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  7. #7
    Registered User
    Join Date
    Dec 2003
    Posts
    92
    very smart solution indeed. i did not want to use structure. i was thinking some other good method. i liked your solution . its allright.
    blue_gene

  8. #8
    Registered User
    Join Date
    Dec 2003
    Posts
    92
    you could use a sentinel value to mark the end of the array


    you shouldn't delete the memory from within the function since it is being used afterward!


    Another thing I noticed was that the function references a global variable. This is almost always a very bad idea. A much better way would be to pass the variable as a parameter

    your coments are very much informative to me. thanks...i will try to use later.
    blue_gene

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  2. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  3. Glib and file manipulation
    By unixOZ in forum Linux Programming
    Replies: 1
    Last Post: 03-22-2004, 09:39 PM
  4. Typecasting a void* to a function pointer
    By Procyon in forum C++ Programming
    Replies: 2
    Last Post: 01-14-2004, 05:43 PM
  5. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM