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) 9 2197
"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
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
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>>
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!
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
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
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
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 =---
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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()
|
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)...
|
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...
|
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...
|
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,...
|
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...
|
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...
|
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...
|
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...
|
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...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM).
In this month's session, the creator of the excellent VBE...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: Aftab Ahmad |
last post by:
Hello Experts!
I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
|
by: Aftab Ahmad |
last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below.
Dim IE As Object
Set IE =...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: marcoviolo |
last post by:
Dear all,
I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| |