473,548 Members | 2,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,st art);

start=malloc(si zeof(*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(filenam e,100);

fp=fopen(filena me,"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 2215
"Richard Hunt" <01******@stude nt.gla.ac.uk> wrote in message
news:18******** *************** ***@posting.goo gle.com...
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,st art);

start=malloc(si zeof(*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(filenam e,100);

fp=fopen(filena me,"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******@stude nt.gla.ac.uk> wrote in message
news:18******** *************** ***@posting.goo gle.com...
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,st art);

start=malloc(si zeof(*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(filenam e,100);

fp=fopen(filena me,"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.pow ernet.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******@studen t.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,st art);

start=malloc(si zeof(*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(filenam e,100);

fp=fopen(filena me,"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,st art);
start=malloc(si zeof(*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********@yah oo.com) (cb********@wor ldnet.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********@yah oo.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",titl e,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,au thor,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******@studen t.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(arg s);

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.c om/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******@studen t.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,au thor,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.ne t
Nov 14 '05 #10

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

Similar topics

66
4909
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
9968
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) from dbo.foo f where f.p = t.y ) FROM dbo.test t
7
6176
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 make it better soon. Unfortunately, there is never a non-crucial time in which we can do an upgrade, so we are stuck for now. Point 1: There are...
4
2628
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 returns one row from a table, and up to 3 rows from another table. I want to read the values of the three rows into an array, but I can't figure out...
3
1292
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, then.." to display one block of HTML in English, and then another block in French? Is there an easy way? Also, "string" itself doesn't support...
2
3637
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 /////////////////////////////////////////////////////////////////////////////////////// <form action="whatever.php" method="post"> <select name="zip_code"...
0
3242
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 instantiate two adoDB connection like this $db1 = &NewAdoConnection ("mysql"); $db1 = &NewAdoConnection ("oracle"); then you can run queries...
11
4326
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 conflicting views and far from ideal solutions. My application has to send small amounts of data about 50bytes to multiple client applications. The...
8
5186
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 more than one value, for example three int-s, I would have to change my "logic" and pass the references to my
17
21547
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 function returned? - To have multiple returns with different values? Which to prefer, and is there a better way? /nergal
0
7518
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7444
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7711
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7954
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7805
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5367
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5085
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3497
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3478
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.