pointer to an array in a function

This is a discussion on pointer to an array in a function within the C Programming forums, part of the General Programming Boards category; Hi, I wanted to find out how i would point to the array arr in function get(char *p) so that ...

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    5

    pointer to an array in a function

    Hi,
    I wanted to find out how i would point to the array arr in function get(char *p) so that i ould print the contents of this array.
    Your help will be appreciated.

    Code:
    int main(){
        char * ptr = NULL:
    
       get(ptr);
       printf("contents: %s:, ptr);
    }
    
    void get(char *p){
        char [5]mm = NULL;
        int i;
    
        for(ii = o;i <5;i++){
             mm[i] = i;
        }
    
        p = mm;  /*I'm not sure about this part */
    }
    Last edited by js_badboy; 09-11-2003 at 09:34 PM.

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,493
    To return arrays you need to malloc them (or return a const char*, I think, don't trust me on that.)

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    "mm" is local to the function only, and when the function exits, it becomes 'invalid' (that is, it may still contain what you put there for some time, but at any moment, the OS may reclaim that chunk and use it for something else).

    The second problem is that get() creates a COPY of the pointer you passed it, so to manipulate the actual pointer, you have to pass it's address. Let's look at the second issue first:


    Code:
    void advance(char * p)
    {
     p++;
    }
    
    int main()
    {
     char buffer[100] = "Hello.";
     char * p = buffer;
     advance(p);
     printf(p);
    }
    Notice that it prints ""Hello.", not "ello." So to accomplish this you have to pass it's address:

    Code:
    void advance(char ** p)
    {
     *p++;
    }
    
    int main()
    {
     char buffer[100] = "Hello.";
     char * p = buffer;
     advance(&p);
     printf(p);
    }
    This would indeed print "ello.".

    So back to the first problem, you CANNOT create a variable within a function, and return it's address, period. Your only options are then to:

    1) pass the variable INTO the function.
    2) return a dynamically allocated variable.
    3) return a static variable.
    4) return a global variable.

    1)
    Code:
    void get(char ** p, char * buffer)
    {
     *p = buffer;
    }
    2)
    Code:
    void get(char ** p)
    {
     *p = malloc(100);
    }
    3)
    Code:
    void get(char ** p)
    {
     static char buffer[100];
     *p = buffer;
    }
    4)
    Code:
    char buffer[100];
    
    void get(char ** p)
    {
     *p = buffer;
    }

    Of these, 3 and 4 are REAL bad practices, 2 can cause memory leaks, and 1 is best.

    But in reality, this sort of function just isn't used. If you need a pointer to something, instead of passing the address of a pointer, just return one:


    Code:
    char * get(char * buffer)
    {
     char * p = buffer;
     return p;
    }
    Notice that although we created 'p' within the function, we didn't return it's address (which would violate good sense). We simply returned THE VALUE of the address that it points to.

    So lets create a real function, and set it up both ways:


    Code:
    void find(char * buffer, char letter, char ** found)
    {
     *found = 0; // signifies 'not found'
     
     int i;
     
        for(i = 0; buffer[i] != 0; ++i)
      {
           if(buffer[i] == letter)
         {
           *found = &buffer[i];
           break;
         }
      }
    }
    
    int main()
    {
     char buffer[100] = "Hello";
     char * found;
     find(buffer, 'e', &found);
     if(found != 0)
      printf("Found it.");
     else
      printf("Not found");
    }


    Next, we will use the more accepted style:


    Code:
    char * find(char * buffer, char letter)
    {
     char * found;
      
     found = 0; // signifies 'not found'
     
     int i;
     
        for(i = 0; buffer[i] != 0; ++i)
      {
           if(buffer[i] == letter)
         {
           found = &buffer[i];
           break;
         }
      }
     return found;
    }
    
    
    int main()
    {
     char buffer[100] = "Hello";
     char * found;
     found = find(buffer, 'e');
     if(found != 0)
      printf("Found it.");
     else
      printf("Not found");
    }

    Did that help any?
    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;
    }

  4. #4
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,161

    Re: pointer to an array in a function

    To correct your code the easy way, simply define ptr as an array, and fix the other syntactical errors:
    Code:
    int main(){
       char ptr[100];
    
       get(ptr);
       printf("contents: %s:, ptr);
       return 0;
    }
    
    void get(char *p){
    //  char [5]mm = NULL;  
        int i;
    
        for(ii = o;i <5;i++){
             ptr[ i ] = i;
        }
    
    //    p = mm;  /*I'm not sure about this part */
    }
    Also, if you are loading the array with integer values, why are you printing as a string?

    It's not good form to post code you want help with that cannot possibly compile, as shown in red. You need to compile and run your code, then post what does not run properly.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  5. #5
    Registered User
    Join Date
    Sep 2003
    Posts
    5
    Thanks alot for your help. I got the code to work. Sorry for the errors. I'm new to C and i thought i could do some declarations like java does. I also noticed that C does not have a string declaration.
    Your help has been greatly appreciated.
    Last edited by js_badboy; 09-12-2003 at 11:44 PM.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No one mentioned making the array static. That's the only real way to return a pointer to an array in a function. Naturally there are a few minor caveats about this method, but it's workable if you don't feel like maloc-ing.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 11-09-2006, 02:28 AM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. a doubt about sending an array to a function
    By louis_mine in forum C Programming
    Replies: 13
    Last Post: 05-14-2005, 11:50 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21