Re: For what reasons?

From: Daniel Schüle (uval_at_rz.uni-karlsruhe.de)
Date: 03/30/05


Date: Wed, 30 Mar 2005 15:13:47 +0200

Bob Jenkins wrote:
> Its not neccessary to return a pointer in a method/function, right ?

you mean .. return pointer from the function
no, not necessary

> But for what reasons/under what circumstances do we have to do that ?

mostly to prevent copying or to be able to *work* with the same object

struct X {
double d;
int i;
char big[1024];
};

// expensive call to foo

X * addToI(X * x, int inc)
{
        x->i += inc;
        return x;
}

X * writeToBig(X * x, const char * what)
{
        strncpy(x->big, what, 1024);
        return x;
}

#include <iostream>
int main()
{
        X x = {0.0, 0, ""};
        writeToBig( addToI(&x, 1) , "hallo World");
        std::cout << x.big << x.big << std::endl;
}

as you can see, you can nest the calls to functions
and you work with the same object
cout verifies the changes

or imagine something like this

char * foo(int number)
{
        static char big[1024];
        sprintf(big, "your number was = %i", number);
        return big;
}
it wouldn't work without static and you would be forced to copy it
somewhere else ..

hope this helps



Relevant Pages

  • Re: Memory Structure Pointer Problems
    ... typedef struct sta { ... char* name; ... int num_cmpnds; ... A pointer to a struct cmp is almost ...
    (comp.lang.c)
  • Re: Insufficient guarantees for null pointers?
    ... will the compiler know what the bounds are after converting that char * ... to an int *, if it could point to either of two arrays which happen to ... compares equal to the original pointer. ...
    (comp.std.c)
  • Re: problem with memcpy and pointers/arrays confusion - again
    ... int line, unsigned long *total_mem) ... That's a long pointer address... ... If sizeof > sizeof which is ... if you allocate for char with sizeof < sizeof, ...
    (comp.lang.c)
  • Re: Request critique of first program
    ... Returns a pointer to an asplit_result struct (unless unable to ... Success is indicated by SUCCESS, ... const char *out_file_b, ... const long int num_lines); ...
    (comp.lang.c)
  • Re: static in [ ]
    ... void someFunc (int size, char a) ... and passing a pointer to fewer than size characters is fine. ...
    (comp.lang.c)