473,395 Members | 1,622 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Multiple returns

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");
}

getline is pretty much as in k&r. closefile is a function
that steps through the linked list, and frees as it goes,
and then closes the file.

I am aware that the filename is not checked before it is
used, this is typed from memory, and I missed out a bit
there. When I finally get internet access on my computer,
I should be able to improve my questions. :)

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?

btw, the complete program is a simple book catalogue program,
I wrote it to practise linked lists, and to write a checkisbn
function. It stores the entries in the linked list in
alphabetical order by author.

This function is the start of my attempt to add file I/O to
store the catalogue. I have not done this before, except for
messing around with graphics functions that output to xpm, so
I want to try to do it properly.

Richard Hunt

(sorry if the formatting is bad---I'm trying to write this in
Google Groups)
Nov 14 '05 #1
9 2204
"Richard Hunt" <01******@student.gla.ac.uk> wrote in message
news:18**************************@posting.google.c om...
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");
}

getline is pretty much as in k&r. closefile is a function
that steps through the linked list, and frees as it goes,
and then closes the file.

I am aware that the filename is not checked before it is
used, this is typed from memory, and I missed out a bit
there. When I finally get internet access on my computer,
I should be able to improve my questions. :)

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?

btw, the complete program is a simple book catalogue program,
I wrote it to practise linked lists, and to write a checkisbn
function. It stores the entries in the linked list in
alphabetical order by author.

This function is the start of my attempt to add file I/O to
store the catalogue. I have not done this before, except for
messing around with graphics functions that output to xpm, so
I want to try to do it properly.

Richard Hunt

(sorry if the formatting is bad---I'm trying to write this in
Google Groups)
Hello,

You can return multiple values from a function by:
1)returning a struct
2)passing parameters by reference

As for second solution, it can be done as:
void createfile()

would become:
void createfile(FILE **fp, Entry **start)
{
/* then you would access each of 'fp' and 'start' as:
*fp = fopen(....)

strcpy(*start->title, "....");

*/
}

HTH,
Elias
Nov 14 '05 #2
lallous wrote:
"Richard Hunt" <01******@student.gla.ac.uk> wrote in message
news:18**************************@posting.google.c om...
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");
}

getline is pretty much as in k&r. closefile is a function
that steps through the linked list, and frees as it goes,
and then closes the file.

I am aware that the filename is not checked before it is
used, this is typed from memory, and I missed out a bit
there. When I finally get internet access on my computer,
I should be able to improve my questions. :)

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?

btw, the complete program is a simple book catalogue program,
I wrote it to practise linked lists, and to write a checkisbn
function. It stores the entries in the linked list in
alphabetical order by author.

This function is the start of my attempt to add file I/O to
store the catalogue. I have not done this before, except for
messing around with graphics functions that output to xpm, so
I want to try to do it properly.

Richard Hunt

(sorry if the formatting is bad---I'm trying to write this in
Google Groups)
Hello,

You can return multiple values from a function


No, you can't, but you can fake it...
by:
1)returning a struct
A struct has a single value, comprising the values of all its members. So
yes, this is one way to fake it.
2)passing parameters by reference
Since C doesn't support passing parameters by reference, this isn't really a
true way to describe the second "fake it" method.

As for second solution, it can be done as:
void createfile()

would become:
void createfile(FILE **fp, Entry **start)
{


This passes a FILE ** by value, and an Entry ** by value. Fortunately, a
copy of a pointer is just as good as the original pointer when it comes to
pointing at stuff, so this "fake it" method works too.

Both your suggestions were useful - it's just your terminology that was a
bit slack. :-)

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #3
On 24 Jan 2004 05:12:32 -0800, 01******@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");
}
snipIf 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>>
Nov 14 '05 #4
Richard Hunt wrote:
.... snip ...
typedef struct entry {
char title[160];
char author[40];
char isbn[14];
struct entry *prev;
struct entry *next;
} Entry;
.... snip ...
This function is the start of my attempt to add file I/O to
store the catalogue. I have not done this before, except for
messing around with graphics functions that output to xpm, so
I want to try to do it properly.


You will not be able to store (or restore from) the links prev and
next in a file. Instead you have to make them implicit, or simply
store the structures contents one by one in a file. This is not a
serious problem when you have a simple linked list, but if you
start handling trees, or anything that makes searching easy, you
will need to worry about it.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #5

On Mon, 26 Jan 2004, CBFalconer wrote:

Richard Hunt wrote:

typedef struct entry {
char title[160];
char author[40];
char isbn[14];
struct entry *prev;
struct entry *next;
} Entry;

... snip ...

This function is the start of my attempt to add file I/O to
store the catalogue. I have not done this before, except for
messing around with graphics functions that output to xpm, so
I want to try to do it properly.


You will not be able to store (or restore from) the links prev and
next in a file. Instead you have to make them implicit, or simply
store the structures contents one by one in a file. This is not a
serious problem when you have a simple linked list, but if you
start handling trees, or anything that makes searching easy, you
will need to worry about it.


I *so* need to start working seriously on 'savestruct' again...
I got it to the point where it parsed struct definitions, and then
stupidly started working on making the output look pretty, rather
than thinking about what sorts of structure it would need to work
with lists/trees/graphs et al. Lack of discipline, that's what it
is... :)
Anyway, <on-topic> good point: writing complex data structures
to files is messy. </on-topic> :-)

-Arthur
Nov 14 '05 #6
CBFalconer <cb********@yahoo.com> wrote in message news:<40***************@yahoo.com>...
Richard Hunt wrote:

... snip ...

typedef struct entry {
char title[160];
char author[40];
char isbn[14];
struct entry *prev;
struct entry *next;
} Entry;

... snip ...

This function is the start of my attempt to add file I/O to
store the catalogue. I have not done this before, except for
messing around with graphics functions that output to xpm, so
I want to try to do it properly.


You will not be able to store (or restore from) the links prev and
next in a file. Instead you have to make them implicit, or simply
store the structures contents one by one in a file. This is not a
serious problem when you have a simple linked list, but if you
start handling trees, or anything that makes searching easy, you
will need to worry about it.


Thanks for your help everybody.

What I was planning to do (I have been taking a couple of days off
from programming) was just read through the linked list and just do:

fprintf(fp,"%s\t%s\t%s\n",title,author,isbn);

for each entry. I assume this will work fine?

and to read in I just do the fscanf version of it?

thanks, Richard
Nov 14 '05 #7
I've just remembered that if I use:

char title[160],author[40],isbn[14];

fscanf("%s\t%s\t%s\n",title,author,isbn);

then if any of the strings contain whitespace, this won't work.
What do I do if I only want the formatting that I give to matter?

Richard
Nov 14 '05 #8
On 24 Jan 2004 05:12:32 -0800, in comp.lang.c ,
01******@student.gla.ac.uk (Richard Hunt) wrote:
What is the best way to get two values back from a function?
define "best".

return a struct if containin the 2 values.
struct twovalues TheFunction(args);

pass in two pointers to data I want to be updated
void TheFunction(int* anintarg, char* achararg);
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?


pass in pointers to them. Works for me.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #9
On 26 Jan 2004 05:56:59 -0800, 01******@student.gla.ac.uk (Richard
Hunt) wrote:
I've just remembered that if I use:

char title[160],author[40],isbn[14];

fscanf("%s\t%s\t%s\n",title,author,isbn);
That can't be right; the first argument to fscanf must be a "stream",
specifically a pointer to FILE (returned by successful fopen, or stdin
or similar). Also, unlimited %s (or %[) in *scanf is a security hole,
just like gets(); better to use e.g. %159s. But see next.
then if any of the strings contain whitespace, this won't work.
What do I do if I only want the formatting that I give to matter?

I'm not sure what "the formatting that [you] give" means. If you mean
you wrote out the data items separated by tab characters and ended by
a newline, perhaps by using >with *printf< the format string you show,
and assuming the data items never contain tab or newline:
n = fscanf (fp, "%159[^\t]%*c%39[^\t]%*c%13[^\n]%*c", <same>)
if( n != 3 ){ <error> }

or if you want to verify that the delimiters are present within the
expected lengths i.e. no attempted overruns:
"%159[^\t]%*1[\t]%39[^\t]%*1[\t]%13[^\n]%1[\n]"
with an additional ,&dummychar and expect count 4.

If it is possible that some tabs are missing (e.g. manually entered or
edited) and you want newline to override so you don't get out of sync,
make the first two (real, in the second variant) classes [^\n\t].

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

66
by: Darren Dale | last post by:
Hello, def test(data): i = ? This is the line I have trouble with if i==1: return data else: return data a,b,c,d = test()
6
by: Steven An | last post by:
Howdy, I need to write an update query with multiple aggregate functions. Here is an example: UPDATE t SET t.a = ( select avg(f.q) from dbo.foo f where f.p = t.y ), t.b = ( select sum(f.q)...
7
by: Rick Caborn | last post by:
Does anyone know of a way to execute sql code from a dynamically built text field? Before beginning, let me state that I know this db architecture is built solely for frustration and I hope to...
4
by: Amy | last post by:
Hello, I've been struggling to learn C#.NET for a while now. I've made some progress, but I'm easily stumped. :( What's stumping me today is this: I've got a stored procedure (SQL) that...
3
by: 00_CuMPe3WaR3D12 | last post by:
I know there is Culture feature with Asp.net, but what I want to know is how to organize/design a web application that supports multiple languages. What is the best approach? Do I use "If,...
2
by: areef.islam | last post by:
Hi, I am kinda new to javascript and I am having this problem with selecting multiple options from a select tag. Hope someone can help me out here. here is my code...
0
by: CountDraculla | last post by:
Fixing Multiple Database bug in adoDB popular data access layer for php, adoDB can support multiple databases from different provider at time, but not from same provider. what I mean is if you...
11
by: Olie | last post by:
This post is realy to get some opinions on the best way of getting fast comunication between multiple applications. I have scowered the web for imformation on this subject and have just found...
8
by: aleksandar.ristovski | last post by:
Hello all, I have been thinking about a possible extension to C/C++ syntax. The current syntax allows declaring a function that returns a value: int foo(); however, if I were to return...
17
by: nergal | last post by:
What is a good programming style in C to handle multiple returns in a function that returns different values? - To have a variable that is set to the return value, which is in the end of the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.