Re: Multiple returns
From: Barry Schwarz (schwarzb_at_deloz.net)
Date: 01/25/04
- Next message: Mike Wahler: "Re: Call to free() sefaults"
- Previous message: Barry Schwarz: "Re: Memory usage v/s complexity -- which one better?"
- In reply to: Richard Hunt: "Multiple returns"
- Next in thread: CBFalconer: "Re: Multiple returns"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 25 Jan 2004 03:30:35 GMT
On 24 Jan 2004 05:12:32 -0800, 0102806h@student.gla.ac.uk (Richard
Hunt) wrote:
>What is the best way to get two values back from a function?
>
>I am working through 'The C Programming Language', but I felt
>like taking a bit of time off to write another program.
>
>The program has global variables:
>extern FILE *fp;
>extern Entry *start;
>
>Entry is defined by:
>
>typedef struct entry {
> char title[160];
> char author[40];
> char isbn[14];
> struct entry *prev;
> struct entry *next;
>} Entry;
>
>This program has a function
>void createfile()
>{
> char filename[100];
>
> if(fp!=NULL)
> closefile(fp,start);
>
> start=malloc(sizeof(*start));
>
> strcpy(start->author,"AAA");
> strcpy(start->title,"AAA");
> strcpy(start->isbn,"0-00-000000-0");
> start->prev=NULL;
> start->next=NULL;
>
> printf("Enter Filename: ");
> getline(filename,100);
>
> fp=fopen(filename,"w");
>}
>
snip
>If I wanted to do this without using the global variables,
>what would be the best way to allow the function to modify
>both values, assuming that they are initialized in the
>parent function?
>
Obviously a function can return only a single value. (If the value is
the aggregate value of a structure then it could have multiple members
but we really don't want to go there.) In order for the function to
update multiple objects in the calling program, the function must know
where those objects are. This is accomplished via pointers.
In the calling function, define the objects createfile() is to update:
FILE *fp = NULL;
Entry *start = NULL;
Call createfile passing the address of each object
createfile(&fp, &start);
The prototype and the function header for createfile() would indicate
that it is receiving pointers to the objects
void createfile(FILE**, Entry**);
and
void createfile(FILE **file, Entry **list){
Every place in your original function where you used the global object
directly, you would now dereference the pointer to the local object in
main. For example, instead of
if(fp!=NULL)
closefile(fp,start);
start=malloc(sizeof(*start));
you would use
if(*file != NULL)
closefile(*file, *list);
*list = malloc(sizeof **list);
<<Remove the del for email>>
- Next message: Mike Wahler: "Re: Call to free() sefaults"
- Previous message: Barry Schwarz: "Re: Memory usage v/s complexity -- which one better?"
- In reply to: Richard Hunt: "Multiple returns"
- Next in thread: CBFalconer: "Re: Multiple returns"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|