Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

pointers, functions & arrays

crazygavcrazygav Member Posts: 8
fairly simple question here basically im still a bit confused about pointers .. . but just wanted to know how to use arrays as arguments for a function and how to return an array from the function.

i think it has to be done by making a pointer to the array(??), but can someone show me how the function would be written (perhaps something simple like take an array and return the exact same array even??)?
thanks!

Comments

  • MT2002MT2002 Member Posts: 1,444
    [b][red]This message was edited by MT2002 at 2004-8-17 9:45:46[/red][/b][hr]
    : fairly simple question here basically im still a bit confused about pointers .. . but just wanted to know how to use arrays as arguments for a function and how to return an array from the function.
    :
    : i think it has to be done by making a pointer to the array(??),
    [BLUE] Exactly.[/BLUE]
    but can someone show me how the function would be written (perhaps something simple like take an array and return the exact same array even??)?
    : thanks!
    :
    [BLUE]Take a look at this example, which uses a function,
    'foo()', which takes in and returns a refrence to the array.
    This example prints out 'ABCDE', a string returned from foo().
    [/BLUE]
    [CODE]
    #include
    #include

    char* foo (char[] ); [GREEN]// prototype. Not actually needed here though
    // Also could be 'char* foo (char*); '
    [/GREEN]
    char* foo (char array[])[GREEN]// This is really a ptr to the array.
    // That is, you could use a 'char*' instead[/GREEN]
    {[GREEN]
    // we get a ptr to the array, and
    // manipluate it as we wish.

    // we dont return an array-we return an address
    // to it

    // just return the array[/GREEN]
    return array;
    }

    int main ()
    {
    char array[5] = {'A','B','C','D','E' };
    [GREEN]
    // pass the array to the function. The returned string will then
    // be printed out[/GREEN]
    printf ("%s", foo (array));

    return 0;
    }[/CODE][BLUE]
    Good Luck!

    ~MT2002[/BLUE]



  • crazygavcrazygav Member Posts: 8
    Thanks!!

    Pretty sure I understood all that :)
Sign In or Register to comment.