Link to home
Start Free TrialLog in
Avatar of higijj
higijj

asked on

returning a ref

Hi!


I created a struct. Now, I want to create a function that will return a pointer to my newly created struct. my question is how to do so? Can I just create a local struct in my function and return it with the & operator?

Here is my simplified struct:
typedef struct {
     char *subject[MAX_SUBJECT];
     char *body[MAX_BODY][LINE_WIDTH];
} creative;

here is my function's prototype:
creative *Initialize_Creative(const char *filename);


so in the body of this function, could I do like:
{
    creative to_return;
    // initialize it from the file

    return &to_return;
}


I don't think this could work, cuz when the function ends, the scope of my struct should go out. So what's the right way to do this?

Thanks a lot,

HiGiJJ!
Avatar of higijj
higijj

ASKER

I have been told alocating the data on the heap using the new operator would do the job.

so

{
creative to_return = new creative;

// initialize it from the file

return to_return;
}

would do the job :)
it certainly will Hiqijj, but I thought this was "C" section rather than C++

regards,

codez80
Avatar of higijj

ASKER

well isn't the above C ?
ASKER CERTIFIED SOLUTION
Avatar of Kocil
Kocil

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of higijj

ASKER

ok

so New is basically just a warper of malloc ?!

Eh, and your struct needs a little bit correction.
Don't use * on the subject and body, if you mean them as array of char.

typedef struct {
    char subject[MAX_SUBJECT];
    char body[MAX_BODY][LINE_WIDTH];
} creative;
Avatar of higijj

ASKER

yteah

I modified it so it looks like

typedef struct {
char *subject;
char *body[LINE_WIDTH];
} creative;
No, new is not JUST a wrapper of malloc.
It is a special C++ operator to create a new object, and it does:
1. automatically calculate the object size (malloc need explicit size)
2. allocate the memory (this is what malloc do).
3. Call the object constructor (malloc won't do this)
Avatar of higijj

ASKER

Thanks for the help/explanation!!

Helped me a lot!

HiGiJJ
Then you should also malloc some memory for the subject and body one by one.

creative* initialize()
{
   creative* c = malloc(sizeof(creative));

   char init_subject[] = "SAMPLE";  

   c->subject = malloc(strlength(init_subject+1));
   strcpy(c->subject, init_subject);
   
   return c;
}


Consequently, you have to free them also 1 by one;
void freeCreative(creative *c)
{
   /* free from the last to the first */

   free(c->body[LAST]);
   ...
   free(c->subject);
   free(c);
}