473,320 Members | 2,111 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,320 software developers and data experts.

Help on understanding Structs

I will have a exam on the oncoming friday, my professor told us that it
will base upon this program. i am having troubles understanding this
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks

#include <stdio.h>
#include <stdlib.h>

typedef struct {
char *name;
int calories;
int group;
} FOOD;

void getFood(FOOD foods[ ], int i ) {
FOOD newFood;
void *characters = malloc(81*sizeof(char));

printf("\nPlease enter the requested information:\n");
printf(" for food item %d, what is\n", i+1);
printf(" the name? ");
gets( characters); // NOTE fgets IS BETTER!
newFood.name = characters;

printf(" calories/serving? ");
scanf("%d", &(newFood.calories));

printf(" food group? ");
scanf("%d", &(newFood.group));
printf("\n");
foods[i] = newFood;

} // end getFood // note:a struct is and lvalue !!

void dump( FOOD foods[ ] , int n ) {
int i;
for(i=0; i<n; i++ ) {
printf("Food %d is: \n", i+1);
printf(" name : %s\n", foods[i].name);
printf(" calories: %d\n", foods[i].calories);
printf(" group # : %d\n", foods[i].group);
printf("\n");
} // end for
} // end dump

int main( ) {
int num; // number of foods entered
int i;
char dum[81];

printf("\nHow many foods will you enter? ");
scanf("%d", &num);

FOOD foods[num];
for( i=0; i<num; i++ ) {
gets(dum); //NOTE: THIS IS HERE BECAUSE OF SCANF
getFood( foods, i );
} // end for

dump( foods, num);
return 0;
} // end main

Nov 17 '05 #1
26 2165
like this:

//......
int total_calories;
int maxcalories;
char maxcaloriesname[81]
//......
total_calories=0;
maxcalories=0;
strcpy(maxcaloriesname,"no");
//......

FOOD foods[num];
for( i=0; i<num; i++ ) {

getFood( foods, i );
// .......
total_calories+=foods[i].calories;
if(foods[i].calories>maxcalories)
{
maxcalories=foods[i].calories;
strcpy(maxcaloriesname,foods[i].name);
}

} // end for
//.....

Nov 17 '05 #2
Bail wrote:
I will have a exam on the oncoming friday, my professor told us that it
will base upon this program.
I had whipped up some code, which works, and pasted it only to
discover, its
thursday!
i am having troubles understanding this
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks

[just too many things I felt i had to comment on so ... ]

1. Don't use gets. Its dangerous. GIYF.
2. Interactive input with scanf is tricky stuff. Search the archive,
with something
like "scanf + string + input + pete ". (pete happens to post some
code I really like)
3. Learn about qsort(). Here's some hint: you will need something like
....

int calcmp( const void *l, const void *r )
{
const FOOD *left = l;
const FOOD *right = r;
if ( left->calories > right->calories )
return 1;
/* fill in the blanks ... */
}

4. You said you're having trouble. Presumably, not with the code you
pasted.
If you understand the code you pasted, the homework should be easy
:)
See ya' on friday.

Nov 17 '05 #3
Suman wrote:
2. Interactive input with scanf is tricky stuff. Search the archive,
with something
like "scanf + string + input + pete ". (pete happens to post some
code I really like)


That way of using scanf, was primarily promoted by Dan Pop.
Dan Pop tended to be very accuarate, but was ...

If I were to say that he had an abrasive personality,
it would not surprise me in the least,
if he were to reply with a logical rebuttal
of how his personality was not abrasive
and how I must be mentally deficient
for even thinking something like that.

--
pete
Nov 17 '05 #4

pete wrote:
[...my ignorance snipped]
That way of using scanf, was primarily promoted by Dan Pop.
Dan Pop tended to be very accuarate, but was ...
Hmm. Appears that I just found much the same. But of course,
post-posting.
If I were to say that he had an abrasive personality,
it would not surprise me in the least,
if he were to reply with a logical rebuttal
of how his personality was not abrasive
and how I must be mentally deficient
for even thinking something like that.


And I thought I'm the only Ogden Nash fan 'round here.

Nov 17 '05 #5
huh? i dont get where to put this code into my program to make it work?

Nov 17 '05 #6
fb
pete wrote:
Suman wrote:

2. Interactive input with scanf is tricky stuff. Search the archive,
with something
like "scanf + string + input + pete ". (pete happens to post some
code I really like)

That way of using scanf, was primarily promoted by Dan Pop.
Dan Pop tended to be very accuarate, but was ...

<snip very accurate description> :-)

Indeed...What ever happened to Dan?
Nov 17 '05 #7
Come on some one help me out here.... dont get this stuffs.

Nov 17 '05 #8
fb
Bail wrote:
Come on some one help me out here.... dont get this stuffs.

Ok...try here...it's not very good, but it is simple:

Structures:
http://members.shaw.ca/ipatters/BeginC_10.html

Other C stuff:
http://members.shaw.ca/ipatters/

Nov 17 '05 #9
thanks for the info. is there any more ??? help a poor student here

Nov 17 '05 #10
Bail wrote:
thanks for the info. is there any more ??? help a poor student here


What info?

Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Nov 18 '05 #11
will someone take the time to explain to me how does the program i
posted above work? and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???

Nov 18 '05 #12
In article <11**********************@o13g2000cwo.googlegroups .com>,
Bail <Ba********@gmail.com> wrote:
:huh? i dont get where to put this code into my program to make it work?

You would put it in at the point that you wanted to,
"add all the total calories that
the user input together. determine which food has the largest calories."
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
Nov 18 '05 #13
In article <11*********************@g47g2000cwa.googlegroups. com>,
Bail <Ba********@gmail.com> wrote:
will someone take the time to explain to me how does the program i
posted above work? and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???


What part of it don't you understand? Do you understand basic
operations with structures? Do you understand the following? If not,
what *specific* lines do you not understand, and what is your best
guess about what those lines are supposed to do?
#include <stdio.h>
typedef struct { int foodno; float foodcalories } FOOD;

void describefood( FOOD thefood ) {
printf( "Food #%d has %f Calories\n", thefood.foodno, thefood.foodcalories );
}

void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );
}

int main(void) {
FOOD firstfood, secondfood;

firstfood.foodno = 1;
firstfood.foodcalories = 1187.3;

secondfood.foodno = 2;
secondfood.foodcalories = 831.88;

describefood( firstfood );
describefoodptr( &secondfood );
}
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
Nov 18 '05 #14
void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );

}
thefoodptr->foodno???

Nov 18 '05 #15
Suman wrote:

pete wrote:

If I were to say that he had an abrasive personality,
it would not surprise me in the least,
if he were to reply with a logical rebuttal
of how his personality was not abrasive
and how I must be mentally deficient
for even thinking something like that.


And I thought I'm the only Ogden Nash fan 'round here.


Most of my English text is in free verse,
and all of my C code is.

--
pete
Nov 18 '05 #16
Bail wrote:

You cut out
typedef struct { int foodno; float foodcalories } FOOD;
and other relevant stuff. From a common sig around comp.lang.c atm:
`Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.'
It's clearer to others what you mean when you quote the bits you're
talking about. Anyway...

void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );

}
thefoodptr->foodno???


FOOD is a typedef for the struct:
typedef struct { int foodno; float foodcalories } FOOD;
An instance of FOOD has members foodno (an integer) and
foodcalories (a float).

If you declared an instance like
FOOD myfood;

You would access those members with:
myfood.foodno
and
myfood.foodcalories

The function you are talking about takes a parameter
(FOOD *thefoodptr)

So thefoodptr is a pointer to an instance of FOOD.

You dereference it to get an instance of food like this:
*thefoodptr /* now an instance of FOOD */
And would get at the members like this:
(*thefoodptr).foodno
and
(*thefoodptr).foodcalories

Except this is an awful syntax, so there is a shorthand
thefoodptr->foodno
The -> means dereference the object to the left (to hopefully
get an instance of a struct) then access the member with the
name on the right.

--
imalone
Nov 18 '05 #17
Bail wrote:
will someone take the time to explain to me how does the program i
posted above work?
There is no program above. Please read one of the over 1000 messages on
this group telling you how to provide context using Google. A search for
the terms "Google context" will find them.

You cannot assume that people have seen previous messages, because they
may not have, nor that they will remember them if they have seen them.
and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???


Load it in to an editor is all I can suggest since I don't have the code
you want to modify.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 18 '05 #18
Bail <Ba********@gmail.com> wrote:
void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );

}
thefoodptr->foodno???

If you need to learn C you should simply go and do it. You cannot learn
from a newsgroup if you don't get the basics at all.
You'ld better look into your C book (if you don't have one, don't bother
to write the exame at all). If you have certain questions about the
-> operator for example somebody in this ng will surely answer it.

Though you should note, that most are not willing to do your homework.
--
Z (zo**********@web.de)
"LISP is worth learning for the profound enlightenment experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days." -- Eric S. Raymond
Nov 18 '05 #19
Bail wrote:
will someone take the time to explain to me how does the program i
posted above work? and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???


Not until you learn to post correctly. SEE BELOW.

Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Nov 18 '05 #20
pete said:
Suman wrote:

And I thought I'm the only Ogden Nash fan 'round here.


Most of my English text is in free verse,
and all of my C code is.


Code is never free;
Constrained by mathematics,
Like a flower's leaves.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Nov 18 '05 #21
Richard Heathfield <in*****@invalid.invalid> writes:
pete said:
Suman wrote:
And I thought I'm the only Ogden Nash fan 'round here.


Most of my English text is in free verse,
and all of my C code is.


Code is never free;
Constrained by mathematics,
Like a flower's leaves.


*applause*

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 18 '05 #22
Richard Heathfield wrote:
pete said:

Suman wrote:
And I thought I'm the only Ogden Nash fan 'round here.


Most of my English text is in free verse,
and all of my C code is.

Code is never free;
Constrained by mathematics,
Like a flower's leaves.

union possible { short prose; short code; }
peculiar, definitely; long shot, granted;

long objections (double take) {
static short idioms,
readability = 0, nothing;

interpunction: peculiar; if (nothing) {} else
but: while (peculiar.prose = definitely.code) continue;
}

signed Skarmander;
Nov 18 '05 #23
Skarmander wrote:

Richard Heathfield wrote:
pete said:

Suman wrote:

And I thought I'm the only Ogden Nash fan 'round here.

Most of my English text is in free verse,
and all of my C code is.

Code is never free;
Constrained by mathematics,
Like a flower's leaves.


Petals!
Nobody cares about calyxes!!!

--
pete
Nov 19 '05 #24
which C book you suggest i buy?

Nov 19 '05 #25
Bail said:
which C book you suggest i buy?


One of these three:

The C Programming Language, 2nd Ed. Kernighan & Ritchie. Prentice Hall,
1988. ISBN 0-13-110362-8 (paperback), or 0-13-110370-9 (hardback).

C Programming: A Modern Approach, K.N.King, W.W.Norton & Company, 1996.
ISBN 0-393-96945-2

C: How to Program, 2nd Ed. Deitel, H.M. & Deitel, P.J. Prentice Hall, 1994.
ISBN: 0-13-226119-7

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Nov 19 '05 #26
Groovy hepcat Bail was jivin' on 16 Nov 2005 21:02:54 -0800 in
comp.lang.c.
Help on understanding Structs's a cool scene! Dig it!
I will have a exam on the oncoming friday, my professor told us that it
I realise I'm too late with this followup, but just in case you're
still wondering about it...
will base upon this program. i am having troubles understanding this
Well, what don't you understand? It's pretty straight forward,
notwithstanding the numerous inadequecies, which I have outlined. Do I
understand correctly that your professor supplied this code? If so, YE
GADS! What's he a professor of, needlepoint?
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks

#include <stdio.h>
#include <stdlib.h>

typedef struct {
char *name;
int calories;
int group;
} FOOD;

void getFood(FOOD foods[ ], int i ) {
FOOD newFood;
void *characters = malloc(81*sizeof(char));
sizeof(char) is 1.
You *must* check the return value of malloc() for a null pointer
(indicating an error). malloc() can fail, y'know; and when it does,
you must not try to dereference the pointer.
Why is characters a pointer to void? If you want to store characters
in the memory it points at, then wouldn't a pointer to char be better?
printf("\nPlease enter the requested information:\n");
printf(" for food item %d, what is\n", i+1);
printf(" the name? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.

fflush(stdout);
gets( characters); // NOTE fgets IS BETTER!
Never use gets(). Just never use gets(). As you (or, presumably your
professor) say in the comment, fgets() is better. Why, then, didn't
you (or he) use fgets()? gets() is a disaster waiting to happen. Never
use it. Use fgets() instead. Never use gets(). Read the FAQ for more
on this; and never use gets(). Just to reiterate: never use gets().
By the way, don't use C++ style comments here. There are (at least)
two good reasons for this. First, many people here still use pre-C99
compilers, which don't support C++ style comments. And second, lines
have a way of wrapping around here. When that happens it makes
cutting, pasting and compiling dificult. Original C comments (/*...*/)
are well behaved when they wrap around. C++ comments are not.
newFood.name = characters;

printf(" calories/serving? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.

fflush(stdout);
scanf("%d", &(newFood.calories));

printf(" food group? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.

fflush(stdout);
scanf("%d", &(newFood.group));
printf("\n");
foods[i] = newFood;
You're not going to return some status value to indicate
success/failure conditions?
} // end getFood // note:a struct is and lvalue !!
What's the point of this useless comment? Comments should make code
clearer, easier to read. They should not just clutter the code with
useless garbage.
void dump( FOOD foods[ ] , int n ) {
int i;
for(i=0; i<n; i++ ) {
printf("Food %d is: \n", i+1);
printf(" name : %s\n", foods[i].name);
printf(" calories: %d\n", foods[i].calories);
printf(" group # : %d\n", foods[i].group);
printf("\n");
} // end for
} // end dump
More useless comments!
int main( ) {
int num; // number of foods entered
And another one!
int i;
char dum[81];

printf("\nHow many foods will you enter? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.

fflush(stdout);
scanf("%d", &num);

FOOD foods[num];
Won't work in pre-C99 implementations, where an array's bounds must
be declared by a constant. Instead, you should use malloc() (and do
remember to check the return value).
for( i=0; i<num; i++ ) {
gets(dum); //NOTE: THIS IS HERE BECAUSE OF SCANF
Huh? What do you (or your prof) mean? You mean scanf() is leaving a
newline (or other garbage) in the stream to be picked up by the next
input function? Well, then, what does that say about the way you are
using scanf()? What does it say about the whole input strategy? Not
very good, is it? Consult the FAQ on this.
Oh, and by the way, did I mention that you should never use gets()?
Well, you should never use gets().
getFood( foods, i );
} // end for

dump( foods, num);
What about relinquishing the memory allocated in getFood()? Very
poor form, leaving this undone!
return 0;
Poor (inconsistent) indentation! This sort of thing can make code
harder to read.
} // end main


If your professor wrote this code, I'd seriously think about
changing schools. It's horrendous! I'd expect a rank beginner to write
code like that, not a professor (unless he were a professor of
something totally unrelated to programming).
But the logic is pretty simple. Here is a basic breakdown of it.

1) First it asks the user to enter the number of foods he/she wishes
to enter, then reads in that number.

2) Next it creates an array of structures used to hold the food data.

3) Then it goes into a loop that calls a function that
a) asks the user the name of the food and reads in the name, having
first allocated memory in which to store it,
b) asks the user for the number of calories and reads in the
number,
c) asks the user for the food group (a number) and reads in the
number, and
d) stores this information in an element of the array.

4) Lastly it calls a function that displays the information stored in
the array.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
Nov 19 '05 #27

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

Similar topics

8
by: cpptutor2000 | last post by:
I am using an STL list to store data packets in a network simulator. The data packets are really C structs, which have other C structs inside them. These structs contain unsigned char arrays of...
3
by: SteveM | last post by:
This is probably an easy answer but since I am fairly new to C++ for some reason I can't see it :-( Any help would be appreciated :-) I have a class: class AClass { public:
8
by: Johnny | last post by:
I need to determine whether a text box contains a value that does not convert to a decimal. If the value does not convert to a decimal, I want to throw a MessageBox to have the user correct the...
39
by: gtippery | last post by:
Newbie-ish questions - I've been away from C for a _long_ time. It seems to me that there ought to be easier (or at least shorter) ways to do what this does. It does compile & run for me (with...
10
by: Angel | last post by:
I'm using several C functions (in a dll) that receive a struct as parameter. Since I'm doing it in C#, I assume I need to recreate the struct in C# in order to call the function with the required...
23
by: Brian | last post by:
I am very new to C# programming and have run into a problem. I apologize for the repost of this article. For some reason, my news reader attached it to an existing thread. First off, I have...
9
by: ^MisterJingo^ | last post by:
I'm new to C# (literally 2 days) and need a bit of help understanding an error. struct Blah { int x; int y; public int X {
24
by: arcticool | last post by:
I had an interview today and I got destroyed :( The question was why have a stack and a heap? I could answer all the practical stuff like value types live on the stack, enums are on the stack, as...
4
by: engggirl3000 | last post by:
I was told to write a function that will read data, in a user defined text file, into a vector of structs. I am not sure where to start with this. Could some one tell me what is a vector of...
0
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...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
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...
0
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...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
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)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.